SqlSessionTemplate
SqlSessionTemplate是MyBatis-Spring的核心。這個類負責管理MyBatis的SqlSession,調用MyBatis的SQL方法,翻譯異常。SqlSessionTemplate是線程安全的,可以被多個DAO所共享使用。
當調用SQL方法時,包含從映射器getMapper()方法返回的方法,SqlSessionTemplate將會保證使用的SqlSession是和當前Spring的事務相關的。此外,它管理session的生命週期,包含必要的關閉,提交或回滾操作。
SqlSessionTemplate實現了SqlSession,這就是說要對MyBatis的SqlSession進行簡易替換。
SqlSessionTemplate通常是被用來替代默認的MyBatis實現的DefaultSqlSession,因爲它不能參與到Spring的事務中也不能被注入,因爲它是線程不安全的。相同應用程序中兩個類之間的轉換可能會引起數據一致性的問題。
SqlSessionTemplate對象可以使用SqlSessionFactory作爲構造方法的參數來創建。
例如:
<!-- 創建sqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml"
p:mapperLocations="classpath:com/mf/*/entity/mapper/*.xml"
p:plugins-ref="pagePlugin" />
<!-- 配置sqlSessionTemplate -->
<bean class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>