• MyBatis-Spring的sqlSessionTemplate


    转自:http://www.cnblogs.com/yhtboke/p/5611375.html

    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. <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
    2.     <constructor-arg index="0" ref="sqlSessionFactory"/>  
    3. </bean>  

    这个bean现在可以直接注入到DAO bean中。你需要在bean中添加一个SqlSession属性,就像下面的代码:

    1. public class UserDaoImpl implements UserDao{  
    2.     private SqlSession sqlSession;  
    3.     public void setSqlSession(SqlSession sqlSession){  
    4.         this.sqlSession = sqlSession;  
    5.     }  
    6.     public User getuser(String userId){  
    7.         return (User)sqlSession.selectOne  
    8.         ("org.mybatis.spring.sample.mapper.UserMapper.getUser",userId);  
    9.     }  
    10. }  

    如下注入SqlSessionTemplate:

    1. <bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">  
    2.     <property name="sqlSession" ref="sqlSession"/>  
    3. </bean>  
  • 相关阅读:
    UVA 10305 Ordering Tasks(拓扑排序)
    UVA 1152 4 Values whose Sum is 0(中途相遇法)
    UVA 1103 Ancient Messages
    HDU 2141 Can you find it?
    POJ 2456 Aggressive cows(二分+贪心)
    Tallest Cow【模拟】
    Tallest Cow【模拟】
    激光炸弹【模拟】
    激光炸弹【模拟】
    激光炸弹【模拟】
  • 原文地址:https://www.cnblogs.com/lycroseup/p/7338421.html
Copyright © 2020-2023  润新知