細(xì)說(shuō) Spring 整合 Mybatis
GitHub:https://github.com/nateshao/ssm/tree/master/116-mybatis-spring
1. 整合環(huán)境搭建
“要實(shí)現(xiàn)MyBatis與Spring的整合,很明顯需要這兩個(gè)框架的JAR包,但是只使用這兩個(gè)框架中所提供的JAR包是不夠的,還需要其他的JAR包來(lái)配合使用,整合時(shí)所需準(zhǔn)備的JAR包具體如下。
Spring框架所需的JAR包
- <dependencies>
- <!-- AOP開(kāi)發(fā)使用的JAR -->
- <dependency>
- <groupId>aopalliance</groupId>
- <artifactId>aopalliance</artifactId>
- <version>1.0</version>
- </dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.9.6</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>5.3.8</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>5.3.7</version>
- </dependency>
- <!-- 4個(gè)核心模塊JAR -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>5.3.8</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>5.3.8</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>5.3.8</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
- <version>5.3.8</version>
- </dependency>
- <!-- JDBC和事務(wù)的JAR -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>5.3.8</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>5.3.8</version>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2</version>
- </dependency>
- </dependencies>
MyBatis與Spring整合的中間JAR
- <!-- MyBatis與Spring整合的中間JAR -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>2.0.6</version>
- </dependency>
數(shù)據(jù)庫(kù)驅(qū)動(dòng)JAR(MySQL)
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.47</version>
- </dependency>
數(shù)據(jù)源所需JAR(DBCP)
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>1.4</version>
- </dependency>
- <dependency>
- <groupId>commons-pool</groupId>
- <artifactId>commons-pool</artifactId>
- <version>1.6</version>
- </dependency>
編寫(xiě)配置文件
- 創(chuàng)建項(xiàng)目116-mybatis-spring,引入maven包
- 編寫(xiě)db.properties
- 編寫(xiě)Spring配置文件applicationContext.xml
- 編寫(xiě)MyBatis配置文件mybatis-config.xml
- 引入log4j.properties
db.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false
- jdbc.username=root
- jdbc.password=123456
- jdbc.maxTotal=30
- jdbc.maxIdle=10
- jdbc.initialSize=5
applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.3.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
- <!--讀取db.properties -->
- <context:property-placeholder location="classpath:db.properties"/>
- <!-- 配置數(shù)據(jù)源 -->
- <bean id="dataSource"
- class="org.apache.commons.dbcp2.BasicDataSource">
- <!--數(shù)據(jù)庫(kù)驅(qū)動(dòng) -->
- <property name="driverClassName" value="${jdbc.driver}" />
- <!--連接數(shù)據(jù)庫(kù)的url -->
- <property name="url" value="${jdbc.url}" />
- <!--連接數(shù)據(jù)庫(kù)的用戶名 -->
- <property name="username" value="${jdbc.username}" />
- <!--連接數(shù)據(jù)庫(kù)的密碼 -->
- <property name="password" value="${jdbc.password}" />
- <!--最大連接數(shù) -->
- <property name="maxTotal" value="${jdbc.maxTotal}" />
- <!--最大空閑連接 -->
- <property name="maxIdle" value="${jdbc.maxIdle}" />
- <!--初始化連接數(shù) -->
- <property name="initialSize" value="${jdbc.initialSize}" />
- </bean>
- <!-- 事務(wù)管理器,依賴于數(shù)據(jù)源 -->
- <bean id="transactionManager" class=
- "org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!--開(kāi)啟事務(wù)注解 -->
- <tx:annotation-driven transaction-manager="transactionManager"/>
- <!--配置MyBatis工廠 -->
- <bean id="sqlSessionFactory"
- class="org.mybatis.spring.SqlSessionFactoryBean">
- <!--注入數(shù)據(jù)源 -->
- <property name="dataSource" ref="dataSource" />
- <!--指定核心配置文件位置 -->
- <property name="configLocation" value="classpath:mybatis-config.xml"/>
- </bean>
- <!--實(shí)例化Dao -->
- <bean id="customerDao" class="com.nateshao.dao.impl.CustomerDaoImpl">
- <!-- 注入SqlSessionFactory對(duì)象實(shí)例-->
- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
- </bean>
- <!-- Mapper代理開(kāi)發(fā)(基于MapperFactoryBean) -->
- <!-- <bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
- <property name="mapperInterface" value="com.nateshao.mapper.CustomerMapper" />
- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
- </bean> -->
- <!-- Mapper代理開(kāi)發(fā)(基于MapperScannerConfigurer) -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.nateshao.mapper" />
- </bean>
- <!-- 開(kāi)啟掃描 -->
- <context:component-scan base-package="com.nateshao.service" />
- </beans>
mybatis-config.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <!--配置別名 -->
- <typeAliases>
- <package name="com.nateshao.po" />
- </typeAliases>
- <!--配置Mapper的位置 -->
- <mappers>
- <mapper resource="mapper/CustomerMapper.xml" />
- <!-- Mapper接口開(kāi)發(fā)方式 -->
- <mapper resource="mapper/CustomerMapperInterface.xml" />
- </mappers>
- </configuration>
log4j.properties
- # Global logging configuration
- log4j.rootLogger=ERROR, stdout
- # MyBatis logging configuration...
- log4j.logger.com.nateshao=DEBUG
- # Console output...
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
這樣一來(lái),環(huán)境加載文件就全了
2. 傳統(tǒng)DAO方式的開(kāi)發(fā)整合
“采用傳統(tǒng)DAO開(kāi)發(fā)方式進(jìn)行MyBatis與Spring框架的整合時(shí),可以使用mybatis-spring包中所提供的SqlSessionTemplate類或SqlSessionDaoSupport類來(lái)實(shí)現(xiàn)。
- SqlSessionTemplate:是mybatis-spring的核心類,它負(fù)責(zé)管理MyBatis的SqlSession,調(diào)用MyBatis的SQL方法。當(dāng)調(diào)用SQL方法時(shí),SqlSessionTemplate將會(huì)保證使用的SqlSession和當(dāng)前Spring的事務(wù)是相關(guān)的。它還管理SqlSession的生命周期,包含必要的關(guān)閉、提交和回滾操作。
- SqlSessionDaoSupport:是一個(gè)抽象支持類,它繼承了DaoSupport類,主要是作為DAO的基類來(lái)使用??梢酝ㄟ^(guò)SqlSessionDaoSupport類的getSqlSession()方法來(lái)獲取所需的SqlSession。
代碼實(shí)現(xiàn)
CustomerDao.java
- public interface CustomerDao {
- // 通過(guò)id查詢客戶
- public Customer findCustomerById(Integer id);
- }
CustomerDaoImpl.java
- public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao {
- // 通過(guò)id查詢客戶
- public Customer findCustomerById(Integer id) {
- return this.getSqlSession().selectOne("com.nateshao.po"
- + ".CustomerMapper.findCustomerById", id);
- }
- }
CustomerMapperInterface.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="com.nateshao.po.CustomerMapper">
- <!--根據(jù)id查詢客戶信息 -->
- <select id="findCustomerById" parameterType="Integer"
- resultType="customer">
- select * from t_customer where id = #{id}
- </select>
- </mapper>
測(cè)試類 DaoTest.java
- package com.nateshao.test;
- import com.nateshao.dao.CustomerDao;
- import com.nateshao.mapper.CustomerMapper;
- import com.nateshao.po.Customer;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * @date Created by 邵桐杰 on 2021/10/26 15:12
- * @微信公眾號(hào) 程序員千羽
- * @個(gè)人網(wǎng)站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description:
- */
- public class DaoTest {
- @Test
- public void findCustomerByIdDaoTest() {
- ApplicationContext act =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 根據(jù)容器中Bean的id來(lái)獲取指定的Bean
- CustomerDao customerDao =
- (CustomerDao) act.getBean("customerDao");
- // CustomerDao customerDao = act.getBean(CustomerDao.class);
- Customer customer = customerDao.findCustomerById(1);
- System.out.println(customer);
- }
- @Test
- public void findCustomerByIdMapperTest() {
- ApplicationContext act =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- CustomerMapper customerMapper = act.getBean(CustomerMapper.class);
- Customer customer = customerMapper.findCustomerByIdOne(1);
- System.out.println(customer);
- }
- }
3. Mapper接口方式的開(kāi)發(fā)整合
“在MyBatis+Spring的項(xiàng)目中,雖然使用傳統(tǒng)的DAO開(kāi)發(fā)方式可以實(shí)現(xiàn)所需功能,但是采用這種方式在實(shí)現(xiàn)類中會(huì)出現(xiàn)大量的重復(fù)代碼,在方法中也需要指定映射文件中執(zhí)行語(yǔ)句的id,并且不能保證編寫(xiě)時(shí)id的正確性(運(yùn)行時(shí)才能知道)。為此,我們可以使用MyBatis提供的另外一種編程方式,即使用Mapper接口編程。
基于MapperFactoryBean的整合
“MapperFactoryBean是MyBatis-Spring團(tuán)隊(duì)提供的一個(gè)用于根據(jù)Mapper接口生成Mapper對(duì)象的類,該類在Spring配置文件中使用時(shí)可以配置以下參數(shù):
- mapperInterface:用于指定接口;
- SqlSessionFactory:用于指定SqlSessionFactory;
- SqlSessionTemplate:用于指定SqlSessionTemplate。如果與SqlSessionFactory同時(shí)設(shè)定,則只會(huì)啟用SqlSessionTemplate。
注意!!!
“雖然使用Mapper接口編程的方式很簡(jiǎn)單,但是在具體使用時(shí)還是需要遵循一些規(guī)范。
- Mapper接口的名稱和對(duì)應(yīng)的Mapper.xml映射文件的名稱必須一致。
- Mapper.xml文件中的namespace與Mapper接口的類路徑相同。
- Mapper接口中的方法名和Mapper.xml中定義的每個(gè)執(zhí)行語(yǔ)句的id相同。
- Mapper接口中方法的輸入?yún)?shù)類型要和Mapper.xml中定義的每個(gè)sql的parameterType的類型相同。
- Mapper接口方法的輸出參數(shù)類型要和Mapper.xml中定義的每個(gè)sql的resultType的類型相同。
“在實(shí)際的項(xiàng)目中,DAO層會(huì)包含很多接口,如果每一個(gè)接口都在Spring配置文件中配置,不但會(huì)增加工作量,還會(huì)使得Spring配置文件非常臃腫。為此,可以采用自動(dòng)掃描的形式來(lái)配置MyBatis中的映射器——采用MapperScannerConfigurer類。
MapperScannerConfigurer類在Spring配置文件中可以配置以下屬性:
- basePackage:指定映射接口文件所在的包路徑,當(dāng)需要掃描多個(gè)包時(shí)可以使用分號(hào)或逗號(hào)作為分隔符。指定包路徑后,會(huì)掃描該包及其子包中的所有文件。
- annotationClass:指定了要掃描的注解名稱,只有被注解標(biāo)識(shí)的類才會(huì)被配置為映射器。
- sqlSessionFactoryBeanName:指定在Spring中定義的SqlSessionFactory的Bean名稱。
- sqlSessionTemplateBeanName:指定在Spring中定義的SqlSessionTemplate的Bean名稱。如果定義此屬性,則sqlSessionFactoryBeanName將不起作用。
- markerInterface:指定創(chuàng)建映射器的接口。
MapperScannerConfigurer的使用非常簡(jiǎn)單,只需要在Spring的配置文件中編寫(xiě)如下代碼:
- <!-- Mapper代理開(kāi)發(fā)(基于MapperScannerConfigurer) -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.nateshao.mapper" />
- </bean>
通常情況下,MapperScannerConfigurer在使用時(shí)只需通過(guò)basePackage屬性指定需要掃描的包即可,Spring會(huì)自動(dòng)的通過(guò)包中的接口來(lái)生成映射器。這使得開(kāi)發(fā)人員可以在編寫(xiě)很少代碼的情況下,完成對(duì)映射器的配置,從而提高開(kāi)發(fā)效率。
4. 測(cè)試事務(wù)
如何進(jìn)行事務(wù)測(cè)試?
在項(xiàng)目中,Service層既是處理業(yè)務(wù)的地方,又是管理數(shù)據(jù)庫(kù)事務(wù)的地方。要對(duì)事務(wù)進(jìn)行測(cè)試,首先需要?jiǎng)?chuàng)建Service層,并在Service層編寫(xiě)添加客戶操作的代碼;然后在添加操作的代碼后,有意的添加一段異常代碼(如int i = 1/0;)來(lái)模擬現(xiàn)實(shí)中的意外情況;最后編寫(xiě)測(cè)試方法,調(diào)用業(yè)務(wù)層的添加方法。這樣,程序在執(zhí)行到錯(cuò)誤代碼時(shí)就會(huì)出現(xiàn)異常。
- @Service
- @Transactional
- public class CustomerServiceImpl implements CustomerService {
- //注解注入CustomerMapper
- @Autowired
- private CustomerMapper customerMapper;
- //添加客戶
- public void addCustomer(Customer customer) {
- this.customerMapper.addCustomer(customer);
- int i=1/0; //模擬添加操作后系統(tǒng)突然出現(xiàn)的異常問(wèn)題
- }
- }
在沒(méi)有事務(wù)管理的情況下,即使出現(xiàn)了異常,數(shù)據(jù)也會(huì)被存儲(chǔ)到數(shù)據(jù)表中;如果添加了事務(wù)管理,并且事務(wù)管理的配置正確,那么在執(zhí)行上述操作時(shí),所添加的數(shù)據(jù)將不能夠插入到數(shù)據(jù)表中。
總結(jié)
這篇文章首先對(duì)MyBatis與Spring框架整合的環(huán)境搭建進(jìn)行了講解,
然后講解了使用傳統(tǒng)DAO方式的開(kāi)發(fā)整合,以及基于Mapper接口方式的開(kāi)發(fā)整合。