Mybatis-Spring基本知識

 Mybatis-Spring是將Mybatis和Spring進行融合的一箇中間層插件,將Mybatis的一些工作交給Spring去做,主要包括SqlSessionFactory的創建、SqlSession的管理、事務管理以及異常的轉化。這裏需要注意一點就是Spring3.0支持iBatis2,但是不支持Mybatis3,因此纔出現Mybatis-Spring,以後如果兼容了,可能也不會需要。

1、SqlSessionFactory的構造

(1)採用Spring的bean配置方式,利用SqlSessionFactoryBean來作爲SqlSessionFactory的工廠,SqlSessionFactoryBean可以配置datasource(Spring的datasource都可以),配置文件,配置mapper xml的路徑等,起到了SqlSessionFactoryBuilder的作用

(2)Mybatis-Spring的用法中,配置的SqlSessionFactory的bean通常作爲屬性傳給SqlSessionDaoSupport的實現類或者SqlSessionTemplate,由它們去管理sqlSession

2、事務使用方式

只需配置Spring提供的事務管理bean,將配置給SqlSessionFactory的datasource配置給該事務管理bean即可

3、SqlSession的使用

最核心的類:SqlSessionTemplate是Mybatis-Spring的核心

(1)負責管理SqlSession,轉換異常,是線程安全的,可以被多個DAO共享使用,保證SqlSession和當前的Spring事務相關,管理SqlSession的生命週期,包括關閉、提交和回滾。SqlSessionTemplate實現SqlSession接口,取代Mybatis默認的SqlSession實現DefaultSqlSession。SqlSessionTemplate可以通過SqlSessionFactory構造,SqlSessionDaoSupport的getSqlSession()返回SqlSessionTemplate,相當於也是通過SqlSessionTemplate實現。

(2)SqlSessionTemplate構造時,也可以傳入ExecutorType作爲參數,指定批量之類的。每個dao都是單例的,其中的sqlSession也就是唯一的,所以SqlSessionTemplate構建好之後,ExecutorType就指定了。

(3)SqlSessionTemplate擁有四個屬性:sqlSessionFactory(構造sqlSession),executorType(定義執行類型),sqlSessionProxy(構造sqlSession的代理實現類),exceptionTranslator(將Mybatis的異常轉化到Spring的DataAccessException異常)

(4)關鍵在於構造函數中SqlSessionTemplate會創建sqlSession的代理,其中配置了攔截器SqlSessionInterceptor做函數的調用攔截,主要完成sqlSession的獲取、提交、關閉之類的操作,sqlSession的獲取和事務有關

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章