【MyBatis框架】mybatis和spring整合

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=""xmlns:xsi="" xmlns:mvc=""xmlns:context=""xmlns:aop="" xmlns:tx=""xsi:schemaLocation=" "><!– 加载配置文件 –><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 mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"""><!– 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实现类继承SqlSessionDaoSupport4.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=""xmlns:xsi="" xmlns:mvc=""xmlns:context=""xmlns:aop="" xmlns:tx=""xsi:schemaLocation=" "><!– 加载配置文件 –><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()得到sqlSessionSqlSession 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是在执行本类所有测试方法之前先调用这个方法@Beforepublic void setup() throws Exception{applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic 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 SqlSessionDEBUG [main] – SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d] was not registered for synchronization because synchronization is not activeDEBUG [main] – Fetching JDBC Connection from DataSourceDEBUG [main] – JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by SpringDEBUG [main] – ==> Preparing: SELECT * FROM USER WHERE id=? DEBUG [main] – ==> Parameters: 1(Integer)DEBUG [main] – <== Total: 1DEBUG [main] – Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d]DEBUG [main] – Returning JDBC Connection to DataSource1:张明明5.mapper代理开发5.1mapper.xml和mapper.javaUserMapper.xml:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"""><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>5.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.mapper.UserMapper;import cn.edu.hpu.ssm.po.User;public class UserMapperTest {private ApplicationContext applicationContext;//注解Before是在执行本类所有测试方法之前先调用这个方法@Beforepublic void setup() throws Exception{applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic 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 SqlSessionDEBUG [main] – SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a] was not registered for synchronization because synchronization is not activeDEBUG [main] – Fetching JDBC Connection from DataSourceDEBUG [main] – JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by SpringDEBUG [main] – ==> Preparing: SELECT * FROM USER WHERE id=? DEBUG [main] – ==> Parameters: 1(Integer)DEBUG [main] – <==Total: 1DEBUG [main] – Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a]DEBUG [main] – Returning JDBC Connection to DataSource1:张明明转载请注明出处:

版权声明:本文为博主原创文章,未经博主允许不得转载。

有的旅行时为了寻找逝去的年华,重温青春的惆怅。

【MyBatis框架】mybatis和spring整合

相关文章:

你感兴趣的文章:

标签云: