MyBatis整合Spring分为下面几个部分
* 配置数据源
* 配置SqlSessionFactory
* 配置SqlSessionTemplate
* 配置Mapper
* 事务处理
配置SqlSessionFactory
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- jdbc.properties 中的key必须定义为 jdbc.username,格式开头的 -->
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 依赖数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 依赖mybatis-config.xml配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
SqlSessionFactory的创建依赖数据源和mybatis-config配置文件(mybatis配置文件中就不需要再配置数据源),classpath表示从类路径下获取,这样就创建了mybatis的上下文
需要注意一点,属性文件注入时候,key必须是jdbc.开头的, 比如jdbc.username,jdbc.password,去掉jdbc.会出错。
SqlSessionFactoryBean的源码,看出mybatis的配置可以IOC进行设置,不必全部写在xml中,再引入,但不建议这么做。
public class SqlSessionFactoryBean
implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent>
{
private Resource configLocation;
private Resource[] mapperLocations;
private DataSource dataSource;
private TransactionFactory transactionFactory;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private boolean failFast;
private Interceptor[] plugins;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
private Class<?> typeAliasesSuperType;
private DatabaseIdProvider databaseIdProvider;
private ObjectFactory objectFactory;
private ObjectWrapperFactory objectWrapperFactory;
配置SqlSessionTemplate
SqlSessionTemplate是一个模板类,通过代理生成SqlSession的代理对象执行数据库操作。
源码看出,创建SqlSessionTemplate需要注入一个SqlSessionFactory
public class SqlSessionTemplate implements SqlSession{
private final SqlSessionFactory sqlSessionFactory;
private final ExecutorType executorType;
private final SqlSession sqlSessionProxy;
private final PersistenceExceptionTranslator exceptionTranslator;
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory)
{
this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
}
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType)
{
this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
}
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator)
{
Assert.notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
Assert.notNull(executorType, "Property 'executorType' is required");
this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
this.sqlSessionProxy = ((SqlSession)Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor(null)));
}
配置:
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
<!-- 指定ExecutorType: simple,batch,resume 默认是simple ,可以不指定 -->
<constructor-arg index="1" value="BATCH"></constructor-arg>
</bean>
直接使用SqlSessionTemplate(可以不看)
直接在Dao层使用,将它注入到Dao中,并实现一个公共的Dao的基类
public class BaseDAOImpl {
public SqlSessionTemplate sqlSessionTemplate;
public SqlSessionTemplate getSqlSessionTemplate() {
return sqlSessionTemplate;
}
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
}
public interface StudentDao {
Student getStudent(Integer id);
List<Student> getStudentList(String name);
int deleteInfo(Integer id);
}
public class StudentDaoImpl extends BaseDAOImpl implements StudentDao {
@Override
public Student getStudent(Integer id) {
Student stu = this.sqlSessionTemplate.selectOne("cn.bing.mybatisTest.StudentDao.getStudent", id);
return stu;
}
@Override
public List<Student> getStudentList(String name) {
List<Student> list = this.sqlSessionTemplate.selectList("cn.bing.mybatisTest.StudentDao.getStudentList", name);
return list;
}
@Override
public int deleteInfo(Integer id) {
int count = this.sqlSessionTemplate.delete("cn.bing.mybatisTest.StudentDao.deleteInfo", id);
return count;
}
}
xml中配置这个Dao
<bean id="studentDao" class="cn.bing.mybatisTest.StudentDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSession"></property>
</bean>
这和IBatis时代的编程方式一致,不建议使用
配置Mapper
大部分场景不建议直接使用SqlSessionTemplate或者SqlSession的方式,而是采用Mapper接口编程的方式,让SqlSession在开发过程中消失。
在MyBatis中,Mapper只需要一个接口,而不是一个实现类,MyBatis会通过动态代理生成一个代理对象来运行。
MyBatis-Spring团队提供了一个MapperFactoryBean类作为中介,可以生成Mapper,配置这个类需要三个参数
* mapperInterface,定制mapper接口
* SqlSessionFactory, 当SqlSessionTemplate属性没有配置时候,才去启用
* SqlSessionTemplate,当被设置时候,SqlSessionFactory将作废
<bean id="studentDao" class = "org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.bing.mapper.StudentMapper"></property>
<!-- sqlSessionTemplate没有设置时候,才会启用 -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<!-- 设置sqlSessionTemplate,sqlSessionFactory设置无效 -->
<property name="sqlSessionTemplate" ref="sqlSession"></property>
</bean>
但是如果存在多个Dao呢?
使用MapperScannerConfigurer,自动扫描的形式来配置映射器
* basePackage属性,指定Spring扫描的Mapper包
* annotationClass属性,表示如果类被这个注解标识的时候,才进行扫描
* sqlSessionFactoryBeanName,指定在Spring中定义sqlSessionFactory的bean名称,如果它被定义,sqlSessionFactory将不起作用
* sqlSessionTemplateBeanName,指定在Spring中定义sqlSessionTemplate的bean名称,如果它被定义
sqlSessionFactoryBeanName将不起作用
* markerInterface,指定是实现了什么接口就认为是Mapper。需要提供一个公共的接口去标识。
在Spring配置中给Dao类加上一个注解@Repository标识,标识是Dao类
@Repository
public interface StudentMapper {
public Student queryStudentByNameAndSex(@Param("name")String stuName,@Param("sex")String sex);
public Student queryStudentInfo(@Param("id")int id);
public int getCount(int id);
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.bing.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
</bean>
配置MapperSannerConfigurer 时候,如果是配置sqlSessionFactory属性,会报错Could not load driver Class
,后面改为sqlSessionFacotryBeanName
关于Could not load driverClass ${jdbc.driverClassName}问题解决方案
配置事务
使用声明式事务配置,有两个解决方法,一种是xml配置使用aop织入事务,还有一种是启用注解@Transactional配置
最终的xml配置_springContext.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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 注解支持 -->
<context:annotation-config></context:annotation-config>
<!-- 扫描包,自动创建bean -->
<context:component-scan base-package="cn.bing.service"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- jdbc.properties 中的key必须定义为 jdbc.username,格式开头的 -->
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 依赖数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 依赖mybatis-config.xml配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.bing.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
</bean>
<!-- 配置事务 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="query*" propagation="REQUIRED" read-only="true" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="add*" propagation="REQUIRED" read-only="false" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="studentServicePointCut" expression="execution (* cn.bing.service..*.*(..))" />
<aop:advisor advice-ref="advice" pointcut-ref="studentServicePointCut" />
</aop:config>
</beans>
出现的问题:
配置MyBatis的MapperScannerConfigurer的属性sqlSessionFactory(会出现bug),改为配置为sqlSessionFactoryBeanName,值为SqlSessionFactory配置的Bean的id
整合SpringMVC
将springContext.xml交给ContextLoaderListener加载,优先于SpringMVC.xml被dispatcher加载
出现的问题
springContext.xml 回去扫描@Service的类
SpringMVC.xml会扫描@Controller的类
两个扫描不能有冲突,否则会出现事务失效的问题
springContext.xml中扫包的时候,加上不能扫描@Controller的类
<context:component-scan base-package="cn.bing.service"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
SpringMVC.xml配置扫包的时候,不能扫描@Service的类
<!-- 配置controller扫描包 -->
<context:component-scan base-package="cn.bing.controller" use-default-filters="false" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!-- !!!最好加上这句让SpringMVC管理的时候排除Service层,避免事务失效的问题。 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>zhibing_mybatis</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springContext.xml</param-value>
</context-param>
<listener>
<description>spring listener</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>springmvc config</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>