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包
java
如图mysql
工程结构:
spring
如图sql
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.xmlapache
<?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.xmlspring-mvc
<!-- 加载映射文件 --> <mappers> <!-- 经过resource方法一次加载一个映射文件 --> <mapper resource="sqlmap/User.xml"/> <!-- 批量加载mapper--> <package name="cn.edu.hpu.ssm.mapper"/> </mappers>
4.2dao(实现类继承SqlSessionDaoSupport)session
dao接口实现类须要注入SqlSessoinFactory,经过spring进行注入。
这里spring声明配置方式,配置dao的bean:
让UserDaoImpl实现类继承SqlSessionDaoSupport
4.3配置dao
首先建立UserDao接口和UserDaoImpl接口实现
UserDao.java:mybatis
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:mvc
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:张明明