细说 Spring 整合 Mybatis

开发 前端
要实现MyBatis与Spring的整合,很明显需要这两个框架的JAR包,但是只使用这两个框架中所提供的JAR包是不够的,还需要其他的JAR包来配合使用,整合时所需准备的JAR包具体如下。

[[434252]]

GitHub:https://github.com/nateshao/ssm/tree/master/116-mybatis-spring

1. 整合环境搭建

“要实现MyBatis与Spring的整合,很明显需要这两个框架的JAR包,但是只使用这两个框架中所提供的JAR包是不够的,还需要其他的JAR包来配合使用,整合时所需准备的JAR包具体如下。

Spring框架所需的JAR包

  1. <dependencies> 
  2.    <!-- AOP开发使用的JAR --> 
  3.     <dependency> 
  4.         <groupId>aopalliance</groupId> 
  5.         <artifactId>aopalliance</artifactId> 
  6.         <version>1.0</version> 
  7.     </dependency> 
  8.  
  9.     <dependency> 
  10.         <groupId>org.aspectj</groupId> 
  11.         <artifactId>aspectjweaver</artifactId> 
  12.         <version>1.9.6</version> 
  13.     </dependency> 
  14.     <dependency> 
  15.         <groupId>org.springframework</groupId> 
  16.         <artifactId>spring-aop</artifactId> 
  17.         <version>5.3.8</version> 
  18.     </dependency> 
  19.     <dependency> 
  20.         <groupId>org.springframework</groupId> 
  21.         <artifactId>spring-aspects</artifactId> 
  22.         <version>5.3.7</version> 
  23.     </dependency> 
  24.     <!-- 4个核心模块JAR --> 
  25.     <dependency> 
  26.         <groupId>org.springframework</groupId> 
  27.         <artifactId>spring-beans</artifactId> 
  28.         <version>5.3.8</version> 
  29.     </dependency> 
  30.     <dependency> 
  31.         <groupId>org.springframework</groupId> 
  32.         <artifactId>spring-context</artifactId> 
  33.         <version>5.3.8</version> 
  34.     </dependency> 
  35.     <dependency> 
  36.         <groupId>org.springframework</groupId> 
  37.         <artifactId>spring-core</artifactId> 
  38.         <version>5.3.8</version> 
  39.     </dependency> 
  40.  
  41.     <dependency> 
  42.         <groupId>org.springframework</groupId> 
  43.         <artifactId>spring-expression</artifactId> 
  44.         <version>5.3.8</version> 
  45.     </dependency> 
  46.     <!-- JDBC和事务的JAR --> 
  47.     <dependency> 
  48.         <groupId>org.springframework</groupId> 
  49.         <artifactId>spring-jdbc</artifactId> 
  50.         <version>5.3.8</version> 
  51.     </dependency> 
  52.     <dependency> 
  53.         <groupId>org.springframework</groupId> 
  54.         <artifactId>spring-tx</artifactId> 
  55.         <version>5.3.8</version> 
  56.     </dependency> 
  57.   <dependency> 
  58.             <groupId>commons-logging</groupId> 
  59.             <artifactId>commons-logging</artifactId> 
  60.             <version>1.2</version> 
  61.     </dependency> 
  62. </dependencies> 

 

MyBatis与Spring整合的中间JAR

  1. <!-- MyBatis与Spring整合的中间JAR   --> 
  2. <dependency> 
  3.     <groupId>org.mybatis</groupId> 
  4.     <artifactId>mybatis-spring</artifactId> 
  5.     <version>2.0.6</version> 
  6. </dependency> 

 

数据库驱动JAR(MySQL)

  1. <dependency> 
  2.     <groupId>mysql</groupId> 
  3.     <artifactId>mysql-connector-java</artifactId> 
  4.     <version>5.1.47</version> 
  5. </dependency> 

 

数据源所需JAR(DBCP)

  1. <dependency> 
  2.     <groupId>commons-dbcp</groupId> 
  3.     <artifactId>commons-dbcp</artifactId> 
  4.     <version>1.4</version> 
  5. </dependency> 
  6. <dependency> 
  7.     <groupId>commons-pool</groupId> 
  8.     <artifactId>commons-pool</artifactId> 
  9.     <version>1.6</version> 
  10. </dependency> 

 

编写配置文件

  • 创建项目116-mybatis-spring,引入maven包

  • 编写db.properties
  • 编写Spring配置文件applicationContext.xml
  • 编写MyBatis配置文件mybatis-config.xml
  • 引入log4j.properties

db.properties

  1. jdbc.driver=com.mysql.jdbc.Driver 
  2. jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false 
  3. jdbc.username=root 
  4. jdbc.password=123456 
  5. jdbc.maxTotal=30 
  6. jdbc.maxIdle=10 
  7. jdbc.initialSize=5 

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" 
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:context="http://www.springframework.org/schema/context" 
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.     http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
  9.     http://www.springframework.org/schema/tx  
  10.     http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 
  11.     http://www.springframework.org/schema/context  
  12.     http://www.springframework.org/schema/context/spring-context-4.3.xsd 
  13.     http://www.springframework.org/schema/aop  
  14.     http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> 
  15.     <!--读取db.properties --> 
  16.     <context:property-placeholder location="classpath:db.properties"/> 
  17.     <!-- 配置数据源 --> 
  18.    <bean id="dataSource"  
  19.             class="org.apache.commons.dbcp2.BasicDataSource"
  20.         <!--数据库驱动 --> 
  21.         <property name="driverClassName" value="${jdbc.driver}" /> 
  22.         <!--连接数据库的url --> 
  23.         <property name="url" value="${jdbc.url}" /> 
  24.         <!--连接数据库的用户名 --> 
  25.         <property name="username" value="${jdbc.username}" /> 
  26.         <!--连接数据库的密码 --> 
  27.         <property name="password" value="${jdbc.password}" /> 
  28.         <!--最大连接数 --> 
  29.         <property name="maxTotal" value="${jdbc.maxTotal}" /> 
  30.         <!--最大空闲连接  --> 
  31.         <property name="maxIdle" value="${jdbc.maxIdle}" /> 
  32.         <!--初始化连接数  --> 
  33.         <property name="initialSize" value="${jdbc.initialSize}" /> 
  34.    </bean> 
  35.    <!-- 事务管理器,依赖于数据源 -->  
  36.    <bean id="transactionManager" class= 
  37.      "org.springframework.jdbc.datasource.DataSourceTransactionManager"
  38.       <property name="dataSource" ref="dataSource" /> 
  39.    </bean>     
  40.     <!--开启事务注解 --> 
  41.    <tx:annotation-driven transaction-manager="transactionManager"/> 
  42.     <!--配置MyBatis工厂 --> 
  43.     <bean id="sqlSessionFactory"  
  44.             class="org.mybatis.spring.SqlSessionFactoryBean"
  45.          <!--注入数据源 --> 
  46.          <property name="dataSource" ref="dataSource" /> 
  47.          <!--指定核心配置文件位置 --> 
  48.           <property name="configLocation" value="classpath:mybatis-config.xml"/> 
  49.    </bean> 
  50.     
  51.    <!--实例化Dao --> 
  52.    <bean id="customerDao" class="com.nateshao.dao.impl.CustomerDaoImpl"
  53.    <!-- 注入SqlSessionFactory对象实例--> 
  54.         <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
  55.    </bean> 
  56.    <!-- Mapper代理开发(基于MapperFactoryBean) --> 
  57.    <!-- <bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
  58.        <property name="mapperInterface" value="com.nateshao.mapper.CustomerMapper" /> 
  59.        <property name="sqlSessionFactory" ref="sqlSessionFactory" />   
  60.    </bean> --> 
  61.    <!-- Mapper代理开发(基于MapperScannerConfigurer) --> 
  62.    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
  63.         <property name="basePackage" value="com.nateshao.mapper" /> 
  64.    </bean> 
  65.     
  66.    <!-- 开启扫描 -->  
  67.    <context:component-scan base-package="com.nateshao.service" /> 
  68.     
  69. </beans> 

 

 

 

 

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-config.dtd"
  4. <configuration> 
  5.     <!--配置别名 --> 
  6.     <typeAliases> 
  7.         <package name="com.nateshao.po" /> 
  8.     </typeAliases> 
  9.     <!--配置Mapper的位置 --> 
  10.  <mappers>  
  11.        <mapper resource="mapper/CustomerMapper.xml" /> 
  12.        <!-- Mapper接口开发方式 --> 
  13.     <mapper resource="mapper/CustomerMapperInterface.xml" /> 
  14.         
  15.  </mappers> 
  16. </configuration> 

 

 

 

log4j.properties

  1. Global logging configuration 
  2. log4j.rootLogger=ERROR, stdout 
  3. # MyBatis logging configuration... 
  4. log4j.logger.com.nateshao=DEBUG 
  5. # Console output... 
  6. log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
  7. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
  8. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 

这样一来,环境加载文件就全了

2. 传统DAO方式的开发整合

“采用传统DAO开发方式进行MyBatis与Spring框架的整合时,可以使用mybatis-spring包中所提供的SqlSessionTemplate类或SqlSessionDaoSupport类来实现。

  • SqlSessionTemplate:是mybatis-spring的核心类,它负责管理MyBatis的SqlSession,调用MyBatis的SQL方法。当调用SQL方法时,SqlSessionTemplate将会保证使用的SqlSession和当前Spring的事务是相关的。它还管理SqlSession的生命周期,包含必要的关闭、提交和回滚操作。
  • SqlSessionDaoSupport:是一个抽象支持类,它继承了DaoSupport类,主要是作为DAO的基类来使用。可以通过SqlSessionDaoSupport类的getSqlSession()方法来获取所需的SqlSession。

代码实现

CustomerDao.java

  1. public interface CustomerDao { 
  2.     // 通过id查询客户 
  3.     public Customer findCustomerById(Integer id); 

CustomerDaoImpl.java

  1. public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao { 
  2.     // 通过id查询客户 
  3.     public Customer findCustomerById(Integer id) { 
  4.         return this.getSqlSession().selectOne("com.nateshao.po" 
  5.                 + ".CustomerMapper.findCustomerById", id); 
  6.     } 

CustomerMapperInterface.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
  4. <mapper namespace="com.nateshao.po.CustomerMapper"
  5.    <!--根据id查询客户信息 --> 
  6.    <select id="findCustomerById" parameterType="Integer" 
  7.            resultType="customer"
  8.       select * from t_customer where id = #{id} 
  9.    </select
  10. </mapper> 

 

 

测试类 DaoTest.java

  1. package com.nateshao.test; 
  2.  
  3. import com.nateshao.dao.CustomerDao; 
  4. import com.nateshao.mapper.CustomerMapper; 
  5. import com.nateshao.po.Customer; 
  6. import org.junit.Test; 
  7. import org.springframework.context.ApplicationContext; 
  8. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  9.  
  10. /** 
  11.  * @date Created by 邵桐杰 on 2021/10/26 15:12 
  12.  * @微信公众号 程序员千羽 
  13.  * @个人网站 www.nateshao.cn 
  14.  * @博客 https://nateshao.gitee.io 
  15.  * @GitHub https://github.com/nateshao 
  16.  * @Gitee https://gitee.com/nateshao 
  17.  * Description: 
  18.  */ 
  19. public class DaoTest { 
  20.     @Test 
  21.     public void findCustomerByIdDaoTest() { 
  22.         ApplicationContext act = 
  23.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  24.         // 根据容器中Bean的id来获取指定的Bean 
  25.         CustomerDao customerDao = 
  26.                 (CustomerDao) act.getBean("customerDao"); 
  27. //      CustomerDao customerDao = act.getBean(CustomerDao.class); 
  28.         Customer customer = customerDao.findCustomerById(1); 
  29.         System.out.println(customer); 
  30.     } 
  31.  
  32.     @Test 
  33.     public void findCustomerByIdMapperTest() { 
  34.         ApplicationContext act = 
  35.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  36.         CustomerMapper customerMapper = act.getBean(CustomerMapper.class); 
  37.         Customer customer = customerMapper.findCustomerByIdOne(1); 
  38.         System.out.println(customer); 
  39.     } 

3. Mapper接口方式的开发整合

“在MyBatis+Spring的项目中,虽然使用传统的DAO开发方式可以实现所需功能,但是采用这种方式在实现类中会出现大量的重复代码,在方法中也需要指定映射文件中执行语句的id,并且不能保证编写时id的正确性(运行时才能知道)。为此,我们可以使用MyBatis提供的另外一种编程方式,即使用Mapper接口编程。

基于MapperFactoryBean的整合

“MapperFactoryBean是MyBatis-Spring团队提供的一个用于根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中使用时可以配置以下参数:

  • mapperInterface:用于指定接口;
  • SqlSessionFactory:用于指定SqlSessionFactory;
  • SqlSessionTemplate:用于指定SqlSessionTemplate。如果与SqlSessionFactory同时设定,则只会启用SqlSessionTemplate。

注意!!!

“虽然使用Mapper接口编程的方式很简单,但是在具体使用时还是需要遵循一些规范。

  1. Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一致。
  2. Mapper.xml文件中的namespace与Mapper接口的类路径相同。
  3. Mapper接口中的方法名和Mapper.xml中定义的每个执行语句的id相同。
  4. Mapper接口中方法的输入参数类型要和Mapper.xml中定义的每个sql的parameterType的类型相同。
  5. Mapper接口方法的输出参数类型要和Mapper.xml中定义的每个sql的resultType的类型相同。

“在实际的项目中,DAO层会包含很多接口,如果每一个接口都在Spring配置文件中配置,不但会增加工作量,还会使得Spring配置文件非常臃肿。为此,可以采用自动扫描的形式来配置MyBatis中的映射器——采用MapperScannerConfigurer类。

MapperScannerConfigurer类在Spring配置文件中可以配置以下属性:

  • basePackage:指定映射接口文件所在的包路径,当需要扫描多个包时可以使用分号或逗号作为分隔符。指定包路径后,会扫描该包及其子包中的所有文件。
  • annotationClass:指定了要扫描的注解名称,只有被注解标识的类才会被配置为映射器。
  • sqlSessionFactoryBeanName:指定在Spring中定义的SqlSessionFactory的Bean名称。
  • sqlSessionTemplateBeanName:指定在Spring中定义的SqlSessionTemplate的Bean名称。如果定义此属性,则sqlSessionFactoryBeanName将不起作用。
  • markerInterface:指定创建映射器的接口。

MapperScannerConfigurer的使用非常简单,只需要在Spring的配置文件中编写如下代码:

  1. <!-- Mapper代理开发(基于MapperScannerConfigurer) --> 
  2. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
  3.      <property name="basePackage" value="com.nateshao.mapper" /> 
  4. </bean> 

 

通常情况下,MapperScannerConfigurer在使用时只需通过basePackage属性指定需要扫描的包即可,Spring会自动的通过包中的接口来生成映射器。这使得开发人员可以在编写很少代码的情况下,完成对映射器的配置,从而提高开发效率。

4. 测试事务

如何进行事务测试?

在项目中,Service层既是处理业务的地方,又是管理数据库事务的地方。要对事务进行测试,首先需要创建Service层,并在Service层编写添加客户操作的代码;然后在添加操作的代码后,有意的添加一段异常代码(如int i = 1/0;)来模拟现实中的意外情况;最后编写测试方法,调用业务层的添加方法。这样,程序在执行到错误代码时就会出现异常。

  1. @Service 
  2. @Transactional 
  3. public class CustomerServiceImpl implements CustomerService { 
  4.     //注解注入CustomerMapper 
  5.     @Autowired 
  6.     private CustomerMapper customerMapper; 
  7.     //添加客户 
  8.     public void addCustomer(Customer customer) { 
  9.         this.customerMapper.addCustomer(customer); 
  10.         int i=1/0; //模拟添加操作后系统突然出现的异常问题 
  11.     } 

在没有事务管理的情况下,即使出现了异常,数据也会被存储到数据表中;如果添加了事务管理,并且事务管理的配置正确,那么在执行上述操作时,所添加的数据将不能够插入到数据表中。

总结

这篇文章首先对MyBatis与Spring框架整合的环境搭建进行了讲解,

然后讲解了使用传统DAO方式的开发整合,以及基于Mapper接口方式的开发整合。

 

责任编辑:武晓燕 来源: 程序员千羽
相关推荐

2020-11-09 10:16:41

Mybatis

2022-11-15 08:10:23

SpringMyBatis底层

2017-05-12 15:47:15

Spring BootMybatis Ann Web

2016-12-14 09:03:34

springhibernate异常

2009-06-18 15:24:08

Spring OSGi

2009-06-19 10:00:37

Struts和Spri

2021-05-19 09:53:16

SpringbootMyBatisMySQL

2009-07-14 16:55:32

MyEclipse S

2009-06-01 10:28:03

SpringOSGi整合

2009-06-25 17:13:51

jBPM与Spring

2009-07-14 14:41:33

Webwork与Spr

2009-07-17 17:16:48

Spring iBAT

2010-08-03 09:15:05

ScalaSpring

2009-08-11 09:47:01

Spring整合Str

2022-12-23 08:28:42

策略模式算法

2021-06-07 08:39:58

SpringBootMyBatisMapper

2023-06-07 08:08:37

MybatisSpringBoot

2009-07-09 18:24:00

WebWork与Spr

2022-07-21 11:04:53

Swagger3Spring

2017-10-17 15:14:33

Spring BooThymeleafWeb
点赞
收藏

51CTO技术栈公众号