MyBatis08-Mybatis与Spring集成(方法二)

Mybatis整合Spring:


在上一篇文章MyBatis04–Mybatis 与 Spring集成(方法一)中,我们介绍了Spring与Mybatis的一种集成方式,其中用到了sqlSessionTemplate,现在,我们使用第二种方式对两者进行整合。

采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供的SqlSession

区别:

1)不需要管理sqlSessionTemplate
2)在Dao的实现中,需要继承SqlSessionDaoSupport


1、将beans.xml中的sqlSessionTemplate删除

<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

2、修改beans.xml中的映射关系

<bean id="userDao" class="cn.edu.ldu.daoImpl.UserDaoImpl">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>

改为:

<bean id="userDao" class="cn.sxt.dao.impl.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

3、修改Dao的实现类:

在这里,我们让UserDaoImpl继承 SqlSessionDaoSupport,利用方法 getSqlSession() 可以得到 SqlSessionTemplate ,从而可以执行各种 SQL 语句。

@Repository
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

    public List<User> selectUser() {
        return this.getSqlSession().selectList("cn.edu.ldu.model.user.mapper.selectAll");
    }

}

也许看到这里,你很不理解继承这个SqlSessionDaoSupport,有什么用,现在,我们看一下它的源码,我想,你会更容易理解一些。

public abstract class SqlSessionDaoSupport extends DaoSupport {

  private SqlSession sqlSession;

  private boolean externalSqlSession;

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    if (!this.externalSqlSession) {
      this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
    }
  }

  public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
    this.sqlSession = sqlSessionTemplate;
    this.externalSqlSession = true;
  }

  public SqlSession getSqlSession() {
    return this.sqlSession;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void checkDaoConfig() {
    notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
  }

}

通过源码,我们可以看出,在SqlSessionDaoSupport这个 类中,给我们封装好了一个方法public void setSqlSessionTemplate(),这是不是就和我们上一篇文章联系在了一起。只不过现在是mybatis-spring给我们封装好了罢了。

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值