目录
原始dao开发与spring整合(SqlSessionDaoSupport)
使用mapper扫描器 MapperScannerConfigurer
整合思路
需要spring通过单例方式管理SqlSessionFactory。
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
持久层的mapper都需要由spring进行管理。
整合环境
创建一个新的java工程(接近实际开发的工程结构)
jar包:
mybatis3.2.7的jar包
spring3.2.0的jar包
mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,mybatis和spring整合由mybatis提供。
全部jar包
配置sqlSessionFactory
在applicationContext.xml配置sqlSessionFactory和数据源
sqlSessionFactory在mybatis和spring的整合包下。
applicationContext.xml
<?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 ">
<!-- bean definitions here -->
<!-- 数据库配置文件 -->
<context:property-placeholder location="db.properties"/>
<!-- 定义数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="userdao" class="cn.pro.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.user=root
jdbc.password=123456
原始dao开发与spring整合(SqlSessionDaoSupport)
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="test">
<!-- 根据id获取用户信息 -->
<select id="findUserById" parameterType="int" resultType="cn.pro.entity.User">
select * from user where id = #{id}
</select>
<!-- 自定义条件查询用户列表 -->
<select id="findUserByUsername" parameterType="cn.pro.entity.User"
resultType="cn.pro.entity.User">
select * from user where username like '%${value}%'
</select>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
<select id="findUserByNameAndSex" parameterType="map" resultType="cn.pro.entity.User">
select * from user where username=#{username} and sex=#{sex}
</select>
</mapper>
在SqlMapconfig.xml中加载User.xml
<?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>
<mappers >
<mapper resource="cn/pro/dao/UserMapper.xml"/>
</mappers>
</configuration>
dao(实现类继承SqlSessionDaoSupport)
dao接口实现类需要注入SqlSessoinFactory,通过spring进行注入。
这里spring声明配置方式,配置dao的bean:
让UserDaoImpl实现类继承SqlSessionDaoSupport
注意SqlSession session = this.getSqlSession();不能当做全局变量使用,只能在方法内部获取,否则会出现空指针异常,坑爹
配置dao上面在applicationcontext.xml中已经配置
测试程序
package cn.pro.dao.impl;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import cn.pro.dao.UserDao;
import cn.pro.entity.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
public User findUserById(int id) throws Exception {
// TODO Auto-generated method stub
SqlSession session = this.getSqlSession();
System.out.println(session);
User user = session.selectOne("test.findUserById",id);
return user;
}
}
日志输出:
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1a7f9dc] 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@1a7f9dc]
DEBUG [main] - Returning JDBC Connection to DataSource
User [id=1, username=王五, sex=2, birthday=null, address=null]
实现mapper代理开发
使用mapperfactorybean逐个注册
需要遵循使用mapper代理开发的规范 名字 命名空间以及方法名和参数
通过MapperFactoryBean创建代理对象
此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。每个mapper接口都需要在spring配置文件中定义
1.在sqlMapConfig.xml中配置mapper.xml的位置
如果mapper.xml和mappre接口的名称相同且在同一个目录,这里可以不用配置
<mappers>
<mapper resource="mapper.xml文件的地址" />
<mapper resource="mapper.xml文件的地址" />
</mappers>
2.定义mapper接口
3.applicationcontext.xml配置
指定接口地址和sqlsessionfactory
此方法问题:
需要针对每个mapper进行配置,麻烦。
通过MapperScannerConfigurer进行mapper扫描(建议使用)
使用mapper扫描器 MapperScannerConfigurer
方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。只需要在spring配置文件中定义一个mapper扫描器,自动扫描包中的mapper接口生成代代理对象。
1.mapper.xml编写
2.定义mapper接口
注意mapper.xml的文件名和mapper的接口名称保持一致,且放在同一个目录
3.配置mapper扫描器
mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
准寻规范:将mapper.java和mapper.xml映射文件名称保持一致并且在同一个目录中
自动扫描出来的mapper的bean的id就是mapper类名(首字母小写)
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper接口包地址"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
basePackage:扫描包路径,中间可以用逗号或分号分隔定义多个包
4使用扫描器后从spring容器中获取mapper的实现对象
如果将mapper.xml和mapper接口的名称保持一致且放在一个目录 则不用在sqlMapConfig.xml中进行配置
spring配置文件
注意配置扫描器时<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>是value而不是ref 不然会报错 坑爹 这个错误找了很久原因是:因为MapperScannerConigurer实际是在解析加载bean定义阶段的,这个时候要是设置sqlSessionFactory的话,会导致提前初始化一些类,这个时候,PropertyPlaceholderConfigurer还没来得及替换定义中的变量,导致把表达式当作字符串复制了。
<?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 ">
<!-- bean definitions here -->
<!-- 数据库配置文件 -->
<context:property-placeholder location="db.properties"/>
<!-- 定义数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置mapper代理自动扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.pro.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
测试:
@Test
public void testmapperscan(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
UserMapper usermap = (UserMapper) context.getBean("userMapper");
User user = usermap.findUserById(1);
System.out.println(user);
}