spring和mybatis整合
1.整合思路
需要spring通过单例方式管理SqlSessionFactory。
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
持久层的mapper都需要由spring进行管理。
2.整合环境
创建一个新的java工程(接近实际开发的工程结构)
jar包:
mybatis3.2.7的jar包
spring3.2.0的jar包
mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,mybatis和spring整合由mybatis提供。jar包名mybatis-spring-1.2.2.jar
下面加入MyBatis与Spring整合的全部jar包
如图
工程结构:
如图
3.sqlSessionFactory
在applicationContext.xml配置sqlSessionFactory和数据源
sqlSessionFactory在mybatis和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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
4.原始dao开发(和spring整合后)
4.1User.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">
<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用 -->
<mapper namespace="test">
<!-- 在映射文件中配置很多sql语句 -->
<!-- 需求:通过id查询用户表的记录 -->
<!-- 通过select执行数据库查询,
id:标示映射文件中的sql,成为Statement的id
将sql语句封装到mappedStatement对象中,所以将id称为statement的id,
parameterType:指定输入参数的类型,
#{}标示一个占位符,
#{id}其中id表示接收输入参数的名称,如果输入参数是简单类型,那么#{}中的值可以任意(如value)。
resultType:指定sql输出结果的映射的java对象类型,
select指定resultType表示将单条记录映射成java对象-->
<select id="findUserById" parameterType="int" resultType="cn.edu.hpu.ssm.po.User">
SELECT * FROM USER WHERE id=#{id}
</select>
</mapper>
在SqlMapconfig.xml中加载User.xml
<!-- 加载映射文件 -->
<mappers>
<!-- 通过resource方法一次加载一个映射文件 -->
<mapper resource="sqlmap/User.xml"/>
<!-- 批量加载mapper-->
<package name="cn.edu.hpu.ssm.mapper"/>
</mappers>
4.2dao(实现类继承SqlSessionDaoSupport)
dao接口实现类需要注入SqlSessoinFactory,通过spring进行注入。
这里spring声明配置方式,配置dao的bean:
让UserDaoImpl实现类继承SqlSessionDaoSupport
4.3配置dao
首先创建UserDao接口和UserDaoImpl接口实现
UserDao.java:
package cn.edu.hpu.ssm.dao;
import cn.edu.hpu.ssm.po.User;
//用户管理的Dao接口
public interface UserDao{
//根据Id查询用户信息
public User findUserById(int id) throws Exception;
}
UserDaoImpl.java:
package cn.edu.hpu.ssm.dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import cn.edu.hpu.ssm.po.User;
public class UserDaoImpl implements UserDao{
//需要向dao实现类中注入SqlSessionFactory工厂
//这里我们暂时没用spring,我们通过构造方法注入
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory=sqlSessionFactory;
}
public User findUserById(int id) throws Exception {
SqlSession sqlSession=sqlSessionFactory.openSession();
User user=sqlSession.selectOne("test.findUserById",id);
//释放资源
sqlSession.close();
return user;
}
}
在applicationContext.xml中配置dao。
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 原始Dao接口 -->
<bean id="userDao" class="cn.edu.hpu.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
让UserDaoImpl去继承SqlSessionDaoSupport类,在SqlSessionDaoSupport类中提供了set和getsqlSessionFactory的方法。
package cn.edu.hpu.ssm.dao;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import cn.edu.hpu.ssm.po.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
public User findUserById(int id) throws Exception {
//继承SqlSessionDaoSupport类,通过this.getSqlSession()得到sqlSession
SqlSession sqlSession=this.getSqlSession();
User user=sqlSession.selectOne("test.findUserById",id);
return user;
}
}
4.4测试程序
package cn.edu.hpu.ssm.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.edu.hpu.ssm.dao.UserDao;
import cn.edu.hpu.ssm.po.User;
public class UserDaoImplTest {
private ApplicationContext applicationContext;
//注解Before是在执行本类所有测试方法之前先调用这个方法
@Before
public void setup() throws Exception{
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception{
UserDao userDao=(UserDao)applicationContext.getBean("userDao");
//调用UserDao的方法
User user=userDao.findUserById(1);
//输出用户信息
System.out.println(user.getId()+":"+user.getUsername());
}
}
测试结果和输出日志:
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d]
DEBUG [main] - Returning JDBC Connection to DataSource
1:张明明
5.mapper代理开发
5.1mapper.xml和mapper.java
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.edu.hpu.ssm.mapper.UserMapper">
<select id="findUserById" parameterType="int" resultType="cn.edu.hpu.mybatis.po.User">
SELECT * FROM USER WHERE id=#{id}
</select>
</mapper>
UserMapper.java:
package cn.edu.hpu.ssm.mapper;
import cn.edu.hpu.ssm.po.User;
//用户管理的Dao接口
public interface UserMapper {
//根据Id查询用户信息
public User findUserById(int id) throws Exception;
}
5.2通过MapperFactoryBean创建代理对象
<!-- mapper配置
MapperFactoryBean根据mapper接口生成mapper代理对象-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- mapperInterface指定mapper接口 -->
<property name="mapperInterface" value="cn.edu.hpu.ssm.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
此方法问题:
需要针对每个mapper进行配置,麻烦。所以要通过MapperScannerConfigurer进行mapper扫描。
5.3通过MapperScannerConfigurer进行mapper扫描(建议使用)
<!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注入
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中.
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果扫描多个包,每个包中间使用半角逗号分隔 -->
<property name="basePackage" value="cn.edu.hpu.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
sqlMapperConfig.xml中的mapper扫描就可以不要了
<!-- 加载映射文件 -->
<mappers>
<!-- 通过resource方法一次加载一个映射文件 -->
<mapper resource="sqlmap/User.xml"/>
<!-- 批量加载mapper
和spring整合后,使用mapper扫描器,这里不需要配置了-->
<!--<package name="cn.edu.hpu.ssm.mapper"/>-->
</mappers>
测试代码
package cn.edu.hpu.ssm.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.edu.hpu.ssm.mapper.UserMapper;
import cn.edu.hpu.ssm.po.User;
public class UserMapperTest {
private ApplicationContext applicationContext;
//注解Before是在执行本类所有测试方法之前先调用这个方法
@Before
public void setup() throws Exception{
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
UserMapper userMapper=(UserMapper)applicationContext.getBean("userMapper");
User user=userMapper.findUserById(1);
System.out.println(user.getId()+":"+user.getUsername());
}
}
测试结果及输出日志
DEBUG [main] - Returning cached instance of singleton bean 'userMapper'
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a]
DEBUG [main] - Returning JDBC Connection to DataSource
1:张明明
来源:oschina
链接:https://my.oschina.net/u/233752/blog/509163