Spring与MyBatis整合
1. 环境搭建
-
所需要的jar包
Spring框架所需要准备的JAR包共10个,其中包括:4个核心模块JAR, AOP开发使用的JAR, JDBC和事务的JAR(其中核心容器依赖的commons-logging的JAR在MyBatis框架的lib包中已经包含,所以这里不必再加入)
由于MyBatis 3在发布之前,Spring 3就已经开发完成,而Spring团队既不想发布基于MyBatis 3的非发布版本的代码,也不想长时间的等待,所以Spring 3以后,就没有对MyBatis 3进行支持。为了满足MyBatis用户对Spring框架的需求,MyBatis社区自己开发了一个用于整合这两个框架的中间件——MyBatis-Spring -
配置文件
1.db.properties文件配置数据库
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.username=Caris
jdbc.password=123456
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
首先定义了读取properties文件的配置,然后配置了数据源,接下来配置了事务管理器并开启了事务注解,最后配置了MyBatis工厂来与Spring整合。其中,MyBatis工厂的作用就是构建SqlSessionFactory,它是通过mybatis-spring包中提供的org.mybatis.spring.SqlSessionFactoryBean类来配置的。通常,在配置时需要提供两个参数:一个是数据源,另一个是MyBatis的配置文件路径。这样Spring的IoC容器就会在初始化id为sqlSessionFactory的Bean时解析MyBatis的配置文件,并与数据源一同保存到Spring的Bean中
2.applicationContext.xml文件配置Spring和数据源
<?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"/>
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driver}"></property>
<property name="url"
value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxTotal" value="${jdbc.maxTotal}"></property>
<property name="maxIdle" value="${jdbc.maxIdle}"></property>
<property name="initialSize" value="${jdbc.initialSize}"></property>
</bean>
<!-- 事务管理器 依赖于数据源 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.dataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 注册事务管理器驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Mybaits工厂配置 -->
<bean id="sqlSessionFactory"
class="org.myBatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 指定核心配置文件位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
</beans>
由于在Spring中已经配置了数据源信息,所以在MyBatis的配置文件中就不再需要配置数据源信息。这里只需要使用< typeAliases>和< mappers>元素来配置文件别名以及指定Mapper文件位置即可
3.mybaits-config.xml文件配置mybaits的Mapper映射
<?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.clarence.po"/>
</typeAliases>
<!-- 配置Mapper -->
<mappers>
</mappers>
</configuration>
2. 传统DAO方式的开发整合
采用传统DAO开发方式进行MyBatis与Spring框架的整合时,我们需要编写DAO接口以及接口的实现类,并且需要向DAO实现类中注入SqlSessionFactory,然后在方法体内通过SqlSessionFactory创建SqlSession。为此,我们可以使用mybatis-spring包中所提供的SqlSessionTemplate类或SqlSessionDaoSupport类来实现此功能
-
SqlSessionTemplate
是mybatis-spring的核心类,它负责管理MyBatis的SqlSession,调用MyBatis的SQL方法。当调用SQL方法时,SqlSessionTemplate将会保证使用的SqlSession和当前Spring的事务是相关的。它还管理SqlSession的生命周期,包含必要的关闭、提交和回滚操作。 -
SqlSessionDaoSupport
是一个抽象支持类,它继承了DaoSupport类,主要是作为DAO的基类来使用。可以通过SqlSessionDaoSupport类的getSqlSession()方法来获取所需的SqlSession
- 实现持久层
1.持久化类
public class Customer {
private Integer id;
private String username;
private String job;
private String phone;
}
2.增加CustomerMapper映射
<?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.clarence.po.CustomerMapper">
<select id="findCustomerById" parameterType="Integer"
resultType="Customer">
select * from t_customer where id=#{id}
</select>
</mapper>
3.mybatis-config增加映射
<mapper resource="com/clarence/po/CustomerMapper.xml"/>
- 实现DAO层
1.定义接口
public interface CustomerDao {
Customer findCustomerById(Integer id);
}
2.实现接口
public class CustomerDaoImpl extends SqlSessionDaoSupport
implements
CustomerDao {
public Customer findCustomerById(Integer id) {
//注1
return this.getSqlSession().selectOne("com.clarence.po.CustomerMapper.findCustomerById",id);
}
}
3.applicationContext.xml添加bean,实例化CustomerDaoImpl
<bean id="customerDao" class="com.clarence.dao.impl.CustomerDaoImpl">
<!-- 注入实例对象 -->
//注2
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
注1:CustomerDaoImpl类继承了SqlSessionDaoSupport类,并实现了CustomerDao接口。其中,SqlSessionDaoSupport类在使用时需要一个SqlSessionFactory或一个SqlSessionTemplate对象,所以需要通过Spring给SqlSessionDaoSupport类的子类对象注入一个SqlSessionFactory或SqlSessionTemplate。这样,在子类中就能通过调用SqlSessionDaoSupport类的getSqlSession()方法来获取SqlSession对象,并使用SqlSession对象中的方法了
注2:创建了一个id为customerDao的Bean,并将SqlSessionFactory对象注入到了该Bean的实例化对象中
测试实现
public void findCustomerByIdDaoTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
// CustomerDao customerDao = (CustomerDao) applicationContext
// .getBean("customerDao");
//两种用法相同
CustomerDao customerDao = applicationContext.getBean(CustomerDao.class);
Customer customer = customerDao.findCustomerById(1);
System.out.println(customer);
}
结果:
3. Mapper接口方式的开发整合
使用传统的DAO开发方式可以实现所需功能,但是采用这种方式在实现类中会出现大量的重复代码,在方法中也需要指定映射文件中执行语句的id,并且不能保证编写时id的正确性(运行时才能知道)
3.1 基于MapperFactoryBean的整合
MapperFactoryBean是MyBatis-Spring团队提供的一个用于根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中使用时可以配置以下参数。
- mapperInterface:用于指定接口
- SqlSessionFactory:用于指定SqlSessionFactory
- SqlSessionTemplate:用于指定SqlSessionTemplate
如果与SqlSessionFactory同时设定,则只会启用SqlSessionTemplate
1.CustomerMapper接口
public interface CustomerMapper {
Customer findCustomerById(Integer id);
}
2.CustomerMapper映射文件
//无变化
<mapper namespace="com.clarence.mapper.CustomerMapper">
<select id="findCustomerById" parameterType="Integer"
resultType="Customer">
select * from t_customer where id=#{id}
</select>
</mapper>
3.mybaits-config引入
<mapper resource="com/clarence/mapper/CustomerMapper.xml"/>
4.appliactionContext配置bean
<bean id = "customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.clarence.mapper.CustomerMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
5.测试类
@Test
public void findCustomerByIdMapperTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
CustomerMapper customerMapper = applicationContext
.getBean(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer);
}
测试结果:
虽然使用Mapper接口编程的方式很简单,但是在具体使用时还是需要遵循以下规范
- Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一致。
- Mapper.xml文件中的namespace与Mapper接口的类路径相同(即接口文件和映射文件需要放在同一个包中)
- Mapper接口中的方法名和Mapper.xml中定义的每个执行语句的id相同
- Mapper接口中方法的输入参数类型要和Mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型要和Mapper.xml中定义的每个sql的resultType的类型相同
3.2 基于MapperScannerConfigurer的整合
MyBatis-Spring团队提供了一种自动扫描的形式来配置MyBatis中的映射器——采用MapperScannerConfigurer类
MapperScannerConfigurer类在Spring配置文件中使用时可以配置以下几个属性·
- basePackage:指定映射接口文件所在的包路径,当需要扫描多个包时可以使用分号或逗号作为分隔符。指定包路径后,会扫描该包及其子包中的所有文件
- annotationClass:指定了要扫描的注解名称,只有被注解标识的类才会被配置为映射器
- sqlSessionFactoryBeanName:指定在Spring中定义的SqlSessionFactory的Bean名称
- sqlSessionTemplateBeanName:指定在Spring中定义的SqlSessionTemplate的Bean名称。如果定义此属性,则sqlSessionFactoryBeanName将不起作用
- markerInterface:指定创建映射器的接口
<!-- mapper代理开发 ,自动映射-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 只需要配置到包即可 -->
<property name="basePackage" value="com.clarence.mapper"/>
</bean>
MapperScannerConfigurer在使用时只需通过basePackage属性指定需要扫描的包即可,Spring会自动地通过包中的接口来生成映射器(因此不需要在mybatis-config.xml中引入,当然也不需要在applicationContext中配置bean)但还是要有对应的xml文件与接口(mapper.xml文件中的每一个操作,都对应接口中的一个同名方法)。
4. 事务管理
在MyBatis+Spring的项目中,事务是由Spring来管理的
1.spring中配置
<!-- 注册事务管理器驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerMapper customerMapper;
@Override
public void addCustomer(Customer customer) {
this.customerMapper.addCustomer(customer);
int i=1/0;
}
}