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> |