MyBatis 3与spring整合之使用SqlSession

SqlSessionTemplate是MyBatis-Spring的核心。这个类负责管理MyBatis的SqlSession。调用MyBatis的SQL方法。

SqlSessionTemplate是线程安全的,可以被多个DAO所共享使用。

SqlSessionTemplate对象可以使用SqlSessionFactory作为构造方法的参数来创建。

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

  <constructor-arg index="0" ref="sqlSessionFactory" />

</bean>

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

public class UserDaoImpl implements UserDao {

  public 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:

<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">

  <property name="sqlSession" ref="sqlSession" />

</bean>

原文地址:https://www.cnblogs.com/man-li/p/4363133.html