一旦我们配置了SqlSessionFactory的bean,我们需要配置SqlSessionTemplate的bean,它是Spring的Bean中线程安全的对象,包含了线程安全的SqlSession对象。因为SqlSessionTemplate提供了线程安全的SqlSession对象,你可以在Spring Bean中分享相同的SqlSessionTemplate.概念上来说,SqlSessionTemplate与Spring DAO模块是相似的。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
现在我们可以注入SqlSessionBean到Spring中的任意Bean中,和运用SqlSession对象去执行SQL映射的声明。
public class StudentDaoImpl implements StudentDao
{
private SqlSession sqlSession;
public void setSqlSession(SqlSession session)
{
this.sqlSession = session;
}
public void createStudent(Student student)
{
StudentMapper mapper =
this.sqlSession.getMapper(StudentMapper.class);
mapper.insertStudent(student);
}
}
如果你是基于XML来配置Spring的Bean,你可以注入SqlSession的Bean到StudentDaoimpl
<bean id="studentDao" class="com.owen.mybatis.dao.StudentDaoImpl">
<property name="sqlSession" ref="sqlSession" />
</bean>
如果你是基于注解来配置的,那么可以使用下面的方法。
@Repository
public class StudentDaoImpl implements StudentDao
{
private SqlSession sqlSession;
@Autowired
public void setSqlSession(SqlSession session)
{
this.sqlSession = session;
}
public void createStudent(Student student)
{
StudentMapper mapper =
this.sqlSession.getMapper(StudentMapper.class);
mapper.insertStudent(student);
}
}
这里还有其它方式去注入SqlSession的对象,你可以继承SqlSessionDaoSupport。这个方法可以让我们执行身体任何自定义的逻辑,除了了执行的映射语句。
public class StudentMapperImpl extends SqlSessionDaoSupport implements
StudentMapper
{
public void createStudent(Student student)
{
StudentMapper mapper =
getSqlSession().getMapper(StudentMapper.class);
mapper.insertAddress(student.getAddress());
//Custom logic
mapper.insertStudent(student);
}
}
<bean id="studentMapper" class="com.owen.mybatis.dao.StudentMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
在这个方法中,我们注入了Sqlsssion对象,获得Mapper的实例 ,和执行映射的语句。这里,Spring将会调用线程安装的SqlSession对象,和执行完之后关掉方法。在下一章节我们将会讲解,MyBatis-Spring提供更好的方法来处理。