MyBatis与Spring结合,将MyBatis中的SqlSessionFactory、SqlSession交由Spring管理。
1. SqlSessionFactoryBean
在MyBatis学习中讲到SqlSessionFactory是它的核心,使用SqlSessionFactoryBuilder来创建。而在MyBatis-Spring中,则使用 SqlSessionFactoryBean 来替代,Spring 将会在应用启动时为你 创建SqlSessionFactory 对象。
MyBatis学习中讲到,从XML中构建SqlSessionFactory需要有四个重要配置:数据源,事务管理器,mapper,typeAliases。构建SqlSessionFactoryBuilder也同样需要这四个重要配置,将下面代码放置在在 Spring 的 XML 配置文件中:
|
dataSource:数据源。
mapperLocations:对应mapper。指定 MyBatis 的XML 映射文件的位置。
typeAliasesPackage:对应typeAliases。指定Java对象的路径。
我们发现没有对应的事务管理器,在下一节写到。
2. 事务
MyBatis-Spring中的事务是利用了已经存在与Spring中的DataSourceTransactionManager,这样MyBatis 就参与到 Spring 的事务管理中。然后我们通常使用的AOP编程也是支持的。
要 开 启 Spring 的事 务 处 理 , 在 Spring 的 XML 配 置 文 件 中 简 单 创 建 一 个 DataSourceTransactionManager 对象:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
利用AOP编程:
<aop:config>
<aop:pointcut id="pc" expression="execution(* com.lili.test.dao..*.*(..)) || execution(* com.lili.common.mybatis..*.*(..))" />
<aop:advisor pointcut-ref="pc" advice-ref="txManager" order="1" />
</aop:config>
3. 使用SqlSessionTemplate实现数据库操作
在MyBatis中使用SqlSessionFactory创建SqlSession,在MyBatis-Spring中使用SqlSessionTemplate来负责管理 MyBatis 的 SqlSession。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> |
这个bean可以直接注入到Dao中使用(baseDao中有一个sqlSessionTemplate属性):
<bean id="testBaseDao" abstract="true"> <property name="sqlSessionTemplate" ref="sqlSessionTemplate" /> </bean> |