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作為構造方法的參數來創建。
1
2
3
|
< bean id = "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" > < constructor-arg index = "0" ref = "sqlSessionFactory" /> </ bean > |
這個bean現在可以直接注入到DAO bean中。你需要在bean中添加一個SqlSession屬性,就像下面的代碼:
1
2
3
4
5
6
7
8
9
10
|
public class UserDaoImpl implements UserDao{ private SqlSession sqlSession; public void setSqlSession(SqlSession sqlSession){ this .sqlSession = sqlSession; } public User getuser(String userId){ return (User)sqlSession.selectOne ( "org.mybatis.spring.sample.mapper.UserMapper.getUser" ,userId); } } |
如下注入SqlSessionTemplate:
1
2
3
|
< bean id = "userDao" class = "org.mybatis.spring.sample.dao.UserDaoImpl" > < property name = "sqlSession" ref = "sqlSession" /> </ bean > |
SqlSessionDaoSupport
SqlSessionDaoSupport是一個抽象的支持類,用來為你提供SqlSession。調用getSqlSession()方法你會得到一個SqlSessionTemplate,這然后可以用于執行SQL方法,就像下面這樣:
1
2
3
4
5
6
|
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{ public User getUser(String userId){ return (User)getSqlSession().selectOne ( "org.mybatis.spring.sample.mapper.UserMapper.getUser" ,userId); } } |
通常MapperFactoryBean是這個類的首選,因為它不需要額外的代碼。但是,如果你需要在DAO中做其它非MyBatis的工作或需要具體的類,那么這個類就是很有用了。SqlSessionDaoSupport需要一個sqlSessionFactory或sqlSessionTemplate屬性來設置。這些被明確地設置或由Spring來自動裝配。如果兩者都被設置了,那么sqlSessionFactory是被忽略的。
假設類UserMapperImpl是SqlSessionDaoSupport的子類,它可以在Spring中進行如下的配置:
1
2
3
|
< bean id = "userMapper" class = "org.mybatis.spring.sample.mapper.UserMapperImpl" > < property name = "sqlSessionFactory" ref = "sqlSessionFactory" /> </ bean > |