Spring 和 Mybatis整合

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

文件結構.png

db.properties文件內容
##oracle 和 mysql 你使用其中一個即可,根據自己的賬號密碼填寫
##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

實體類 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 {
/**
 * 新增數據
 *@param user
 */
int insertUser(User user);
/**
 * 更新數據
 *@param user
 */
int updateUser(User user);
 /**
 *  刪除數據
 *@param user
 */
int deleteUser(User user);
/**
 * 根據name 查詢
 *@param name
 */
List<User> getUserByName(String name);

}

業務層 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);
 /**
 * 根據id用戶
 *@param name
 */
void dropUser(Integer id);

}

UserServiceImpl是 UserService 的實現類

@Service // spring容器管理對象 Spring 的注解開發
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"
>

<!-- 配置文件描述標簽 -->
<description>
    <![CDATA[
        描述內容. 配置Spring整合MyBatis技術中的基礎數據
        如 : 數據源
    ]]>
</description>

<!-- 使用spring的技術,讀取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>

<!-- 數據源, 如果spring容器讀取了properties配置文件內容. 那么可以通過springEL表達式中的${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>
<!-- 數據源, 如果不寫配置文件就直接一一對應上也行
 -->
</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"
>

<!-- 配置文件描述標簽 -->
<description>
    <![CDATA[
        描述內容. 配置MyBatis中SqlSessionFactory的配置文件.
    ]]>
</description>

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

<!-- 第二種配置方案
    自動掃描basePackage中的接口和XML配置文件.實現動態代理對象的創建.
    相當于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"
>

<!-- 配置文件描述標簽 -->
<description>
    <![CDATA[
        描述內容. 配置掃描Service的標簽
    ]]>
</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"
>

<!-- 配置文件描述標簽 -->
<description>
    <![CDATA[
        描述內容. 配置事務管理,聲明式事務管理.
    ]]>
</description>

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

<!-- 定義一套通知,實現事務的細粒度管理. -->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
    <!-- 配置事務管理通知屬性. -->
    <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">

<!-- 增加一個新的屬性.可選屬性.
    parameterType - 可選屬性. 用來明確定義,當前方法的輸入參數具體類型是什么.
        常用配置為 : 自定義類型,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>

<!-- 更新數據 -->
<update id="updateUser">
    update tb_user
        <!-- set標簽. 動態設置set語法結構.可以自動刪除最后一個逗號.類似where標簽的功能. -->
        <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>
 <!-- 刪除數據 -->
<delete id="deleteUser">
    delete from tb_user
        where id = #{id}
</delete>
<!-- 同構 id 查找數據 -->
<select id="getUserByName" resultType="User">
    select id, name, password, age
        from tb_user
        where name = #{name}
</select>

</mapper>

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

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());
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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