SqlSessionDaoSupport与SqlSessionTemplate对比

SqlSessionDaoSupport与SqlSessionTemplate对比

SqlSession(SqlSessionDaoSupport类)

SqlSessionDaoSupport

SqlSessionDaoSupport是一个抽象的支持类,用来为你提供SqlSession。调用getSqlSession()方法你会得到一个SqlSessionTemplate,这然后可以用于执行SQL方法,就像下面这样:

Java代码
  1. publicclassUserDaoImplextendsSqlSessionDaoSupportimplementsUserDao{
  2. publicUsergetUser(StringuserId){
  3. return(User)getSqlSession().selectOne
  4. ("org.mybatis.spring.sample.mapper.UserMapper.getUser",userId);
  5. }
  6. }

通 常MapperFactoryBean是这个类的首选,因为它不需要额外的代码。但是,如果你需要在DAO中做其它非MyBatis的工作或需要具体的 类,那么这个类就是很有用了。SqlSessionDaoSupport需要一个sqlSessionFactory或 sqlSessionTemplate属性来设置。这些被明确地设置或由Spring来自动装配。如果两者都被设置了,那么 sqlSessionFactory是被忽略的。

假设类UserMapperImpl是SqlSessionDaoSupport的子类,它可以在Spring中进行如下的配置:

Java代码
  1. <beanid="userMapper"class="org.mybatis.spring.sample.mapper.UserMapperImpl">
  2. <propertyname="sqlSessionFactory"ref="sqlSessionFactory"/>
  3. </bean>

 

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作为构造方法的参数来创建。

Xml代码
  1. <beanid="sqlSession"class="org.mybatis.spring.SqlSessionTemplate">
  2. <constructor-argindex="0"ref="sqlSessionFactory"/>
  3. </bean>

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

Java代码
  1. publicclassUserDaoImplimplementsUserDao{
  2. privateSqlSessionsqlSession;
  3. publicvoidsetSqlSession(SqlSessionsqlSession){
  4. this.sqlSession=sqlSession;
  5. }
  6. publicUsergetuser(StringuserId){
  7. return(User)sqlSession.selectOne
  8. ("org.mybatis.spring.sample.mapper.UserMapper.getUser",userId);
  9. }
  10. }

如下注入SqlSessionTemplate:

Xml代码
  1. <beanid="userDao"class="org.mybatis.spring.sample.dao.UserDaoImpl">
  2. <propertyname="sqlSession"ref="sqlSession"/>
  3. </bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值