Spring 和 Mybatis整合

最近閑來無事應(yīng)朋友只需,整理了一下以前學(xué)習(xí)Spring框架和 Mybatis 框架的一些資料,自己寫了一個(gè)小的單表增刪查改的 dome.
在寫之前需要需要下載好Spring的jar包和 Mybatis的 jar包,在 Mysql 建一個(gè) tb_user 的單表.
下面是工程的一個(gè)包結(jié)構(gòu):

文件結(jié)構(gòu).png

db.properties文件內(nèi)容
##oracle 和 mysql 你使用其中一個(gè)即可,根據(jù)自己的賬號密碼填寫
##oracle
##url=jdbc:oracle:thin:@localhost:1521:orcl
##user=scott
##pwd=12345
##driver=oracle.jdbc.OracleDriver

##mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pwd=root

實(shí)體類 User類

public class User {
      
private Integer id;
private String name;
private String password;
private int age;
public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

}

Usermapper接口類

public interface UserMapper {
/**
 * 新增數(shù)據(jù)
 *@param user
 */
int insertUser(User user);
/**
 * 更新數(shù)據(jù)
 *@param user
 */
int updateUser(User user);
 /**
 *  刪除數(shù)據(jù)
 *@param user
 */
int deleteUser(User user);
/**
 * 根據(jù)name 查詢
 *@param name
 */
List<User> getUserByName(String name);

}

業(yè)務(wù)層 service 的 UserService 接口

public interface UserService {
 /**
 *注冊
 *@param name
 */
public void register(User user); 
 /**
 * 通過姓名查詢用戶
 *@param name
 */
public List<User> getUserByName(String name);
 /**
 * 修改用戶
 *@param name
 */
void modifyUser(User user);
 /**
 * 根據(jù)id用戶
 *@param name
 */
void dropUser(Integer id);

}

UserServiceImpl是 UserService 的實(shí)現(xiàn)類

@Service // spring容器管理對象 Spring 的注解開發(fā)
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
public void register(User user) {
    userMapper.insertUser(user);
}

@Override
public List<User> getUserByName(String name) {
    return this.userMapper.getUserByName(name);
}

@Override
public void modifyUser(User user) {
    this.userMapper.updateUser(user);
}

@Override
public void dropUser(Integer id) {
    User user = new User();
    user.setId(id);
    this.userMapper.deleteUser(user);
}
}

applicationContext-base.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd"
>

<!-- 配置文件描述標(biāo)簽 -->
<description>
    <![CDATA[
        描述內(nèi)容. 配置Spring整合MyBatis技術(shù)中的基礎(chǔ)數(shù)據(jù)
        如 : 數(shù)據(jù)源
    ]]>
</description>

<!-- 使用spring的技術(shù),讀取properties配置文件. -->
<bean id="placeholder" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:cn/sxt/config/commons/db.properties</value>
        </array>
    </property>
</bean>

<!-- 數(shù)據(jù)源, 如果spring容器讀取了properties配置文件內(nèi)容. 那么可以通過springEL表達(dá)式中的${key}
    訪問properties配置文件的value
 -->
<bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${driver}" />
    <property name="url" value="${url}" />
    <property name="username" value="${user}" />
    <property name="password" value="${pwd}" />
</bean>
<!-- 數(shù)據(jù)源, 如果不寫配置文件就直接一一對應(yīng)上也行
 -->
</beans>

applicationContext-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd"
>

<!-- 配置文件描述標(biāo)簽 -->
<description>
    <![CDATA[
        描述內(nèi)容. 配置MyBatis中SqlSessionFactory的配置文件.
    ]]>
</description>

<!-- 配置SqlSessionFactory. 導(dǎo)入了一個(gè)mybatis-spring-x.x.x.jar
    在jar包中,定義了spring和mybatis整合相關(guān)的類型.
 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations">
        <array>
            <!-- 導(dǎo)入目錄cn/sxt/mapper/中的所有xml配置文件. -->
            <value>classpath:cn/sxt/mapper/*.xml</value>
        </array>
    </property>
    <property name="typeAliasesPackage">
        <value>cn.sxt.entity</value>
    </property>
</bean>

<!-- 第二種配置方案
    自動(dòng)掃描basePackage中的接口和XML配置文件.實(shí)現(xiàn)動(dòng)態(tài)代理對象的創(chuàng)建.
    相當(dāng)于MapperFactoryBean的簡寫.
 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.sxt.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!-- 第一種配置方案 -->
<!-- <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" 
    abstract="true" lazy-init="true">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

<bean id="userMapper" parent="baseMapper">
    <property name="mapperInterface" value="cn.sxt.mapper.UserMapper" />
</bean> -->

</beans>

applicationContext-service.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd"
>

<!-- 配置文件描述標(biāo)簽 -->
<description>
    <![CDATA[
        描述內(nèi)容. 配置掃描Service的標(biāo)簽
    ]]>
</description>
    <!-- 掃描包 -->
<context:component-scan base-package="cn.sxt.service" />
</beans>

applicationContext-tx.xml

  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"    
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd"
>

<!-- 配置文件描述標(biāo)簽 -->
<description>
    <![CDATA[
        描述內(nèi)容. 配置事務(wù)管理,聲明式事務(wù)管理.
    ]]>
</description>

<!-- 配置一個(gè)事務(wù)管理器.是一個(gè)Spring定義好的java類.
    MyBatis是一個(gè)輕量級封裝的框架.封裝的級別比較輕.層次少.對JDBC的封裝少.
    MyBatis框架對事務(wù)管理,都是借助JDBC實(shí)現(xiàn)的.
    使用的事務(wù)管理器,就是DataSourceTransactionManager.
 -->
<bean id="transactionManager" 
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 定義一套通知,實(shí)現(xiàn)事務(wù)的細(xì)粒度管理. -->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
    <!-- 配置事務(wù)管理通知屬性. -->
    <tx:attributes>
        <tx:method name="register" isolation="DEFAULT" propagation="REQUIRED"
            rollback-for="java.lang.Exception"/>
        <tx:method name="getUserByName" read-only="true"/>
        <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED"
            rollback-for="java.lang.Exception"/>
        <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED"
            rollback-for="java.lang.Exception"/>
        <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED"
            rollback-for="java.lang.Exception"/>
        <tx:method name="get*" read-only="true"/>
        <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED"
            rollback-for="java.lang.Exception"/>
    </tx:attributes>
</tx:advice>

<!-- 配置切面 -->
<aop:config>
    <aop:advisor advice-ref="txAdvice" 
        pointcut="execution(* cn.sxt.service.*.*(..))"/>
</aop:config>

</beans>

UserMapper.xml

  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.sxt.mapper.UserMapper">

<!-- 增加一個(gè)新的屬性.可選屬性.
    parameterType - 可選屬性. 用來明確定義,當(dāng)前方法的輸入?yún)?shù)具體類型是什么.
        常用配置為 : 自定義類型,Map集合類型,簡單類型.
 -->
<insert id="insertUser" parameterType="cn.sxt.entity.User">
    insert into tb_user (id, name, password, age)
        values(seq_user.nextVal, #{name}, #{password}, #{age})
</insert>

<!-- 更新數(shù)據(jù) -->
<update id="updateUser">
    update tb_user
        <!-- set標(biāo)簽. 動(dòng)態(tài)設(shè)置set語法結(jié)構(gòu).可以自動(dòng)刪除最后一個(gè)逗號.類似where標(biāo)簽的功能. -->
        <set>
            <if test="name != null">
            name = #{name},
            </if>
            <if test="password != null">
            password = #{password},
            </if>
            <if test="age != 0">
            age = #{age},
            </if>
        </set>
        <where>
            <if test="id != null">
            and id = #{id}
            </if>
        </where>
</update>
 <!-- 刪除數(shù)據(jù) -->
<delete id="deleteUser">
    delete from tb_user
        where id = #{id}
</delete>
<!-- 同構(gòu) id 查找數(shù)據(jù) -->
<select id="getUserByName" resultType="User">
    select id, name, password, age
        from tb_user
        where name = #{name}
</select>

</mapper>

接下來我們做測試,建一個(gè)測試類,到如一個(gè) JUnit jar包
也可以用 main 做測試也行,測試就不詳細(xì)說了.看代碼.

public class TestSpringMyBatis {

@Test
public void testUpdate(){
    ApplicationContext context = 
            new ClassPathXmlApplicationContext("classpath:cn/lx/configurations/spring/applicationContext-*.xml");
    
    UserService userService = context.getBean(UserService.class);
    
    User user = new User();
    user.setId(3);
    user.setName("老宋");
    
    userService.modifyUser(user);
}

@Test
public void testInsert(){
    ApplicationContext context = 
            new ClassPathXmlApplicationContext("classpath:cn/lx/configurations/spring/applicationContext-*.xml");
    
    UserService userService = context.getBean(UserService.class);
    
    User user = new User();
    user.setName("天王");
    user.setPassword("xoxo");
    user.setAge(18);
    
    userService.register(user);
}

@Test
public void testService(){
    ApplicationContext context = 
            new ClassPathXmlApplicationContext("classpath:cn/lx/configurations/spring/applicationContext-*.xml");
    
    UserService userService = context.getBean(UserService.class);
    
    System.out.println(userService.getClass().getName());
    
    List<User> users = userService.getUserByName("老王");
    for(User u : users){
        System.out.println(u.getId() + " ; " + u.getName());
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末季率,一起剝皮案震驚了整個(gè)濱河市逆巍,隨后出現(xiàn)的幾起案子祭饭,更是在濱河造成了極大的恐慌绘趋,老刑警劉巖钞它,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件悼尾,死亡現(xiàn)場離奇詭異牌废,居然都是意外死亡廉侧,警方通過查閱死者的電腦和手機(jī)页响,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進(jìn)店門篓足,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拘泞,你說我怎么就攤上這事纷纫。” “怎么了陪腌?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵辱魁,是天一觀的道長。 經(jīng)常有香客問我诗鸭,道長染簇,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任强岸,我火速辦了婚禮锻弓,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蝌箍。我一直安慰自己青灼,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布妓盲。 她就那樣靜靜地躺著杂拨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪悯衬。 梳的紋絲不亂的頭發(fā)上弹沽,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天,我揣著相機(jī)與錄音筋粗,去河邊找鬼策橘。 笑死,一個(gè)胖子當(dāng)著我的面吹牛娜亿,可吹牛的內(nèi)容都是我干的丽已。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼买决,長吁一口氣:“原來是場噩夢啊……” “哼促脉!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起策州,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎宫仗,沒想到半個(gè)月后够挂,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡藕夫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年孽糖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了枯冈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,739評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡办悟,死狀恐怖尘奏,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情病蛉,我是刑警寧澤炫加,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站铺然,受9級特大地震影響俗孝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜魄健,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一赋铝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧沽瘦,春花似錦革骨、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至绿满,卻和暖如春臂外,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背喇颁。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工漏健, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人橘霎。 一個(gè)月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓蔫浆,卻偏偏與公主長得像,于是被迫代替她去往敵國和親姐叁。 傳聞我的和親對象是個(gè)殘疾皇子瓦盛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)外潜,斷路器原环,智...
    卡卡羅2017閱讀 134,652評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,806評論 6 342
  • 一定要下載源碼自己去琢磨,自己配置一遍 GitHub下載這個(gè)工程 談到SSM处窥,我在網(wǎng)上看了很多整合教程嘱吗,我也跟著一...
    伽娃程序猿閱讀 4,007評論 0 14
  • 整合思路 需要spring通過單利方式管理sqlSessionFactoryspring和mybatis整合生成代...
    Stringer閱讀 200評論 0 0
  • 爸爸:我要上班了,寶寶拜拜 寶寶:爸爸拜拜(關(guān)上門快速跑到窗臺上打開窗戶) 寶寶:(看到剛出單元門的爸爸大聲喊)爸...
    月月媽媽閱讀 145評論 0 0