MyBatis集合Spring(二)之SqlSession

一旦我们配置了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提供更好的方法来处理。








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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值