您的位置:首页 > 编程语言 > Java开发

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

2017-02-23 19:12 148 查看
Mybatis整合Spring:

MyBatis04–Mybatis 与 Spring集成(方法一)

MyBatis04–Mybatis 与 Spring集成(方法二)

MyBatis04–Mybaits与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给我们封装好了罢了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: