MyBatis集合Spring(二)之SqlSession
来源:互联网 发布:淘宝上gtx660是新货吗 编辑:程序博客网 时间:2024/06/09 21:03
一旦我们配置了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>
如果你是基于注解来配置的,那么可以使用下面的方法。
@Repositorypublic class StudentDaoImpl implements StudentDao{private SqlSession sqlSession;@Autowiredpublic 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 implementsStudentMapper{public void createStudent(Student student){StudentMapper mapper =getSqlSession().getMapper(StudentMapper.class);mapper.insertAddress(student.getAddress());//Custom logicmapper.insertStudent(student);}}
<bean id="studentMapper" class="com.owen.mybatis.dao.StudentMapperImpl"><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>
在这个方法中,我们注入了Sqlsssion对象,获得Mapper的实例 ,和执行映射的语句。这里,Spring将会调用线程安装的SqlSession对象,和执行完之后关掉方法。在下一章节我们将会讲解,MyBatis-Spring提供更好的方法来处理。
0 0
- MyBatis集合Spring(二)之SqlSession
- Mybatis源码(二)之Spring整合mybatis创建SqlSession
- mybatis-spring深入学习之SqlSession
- Mybatis-Spring 的高级配置(SqlSession)
- MyBatis-Spring-SqlSession
- MyBatis-Spring-SqlSession
- MyBatis-Spring-SqlSession
- Mybatis(二)-----------------Sqlsession
- (四)MyBatis源码解析之SqlSession
- 【SSM】Mybatis之SqlSession
- Mybatis 之 SqlSession
- MyBatis(二) 使用MyBatis改写及SqlSession
- 读mybatis源码之二:构建SqlSession逻辑
- myBatis源码学习之SqlSession
- mybatis使用之SqlSession获取
- MyBatis集合Spring(三)之mapper
- Mybatis源码(三)之SqlSession执行流程全貌
- Spring-MyBatis实战之 Manual close is not allowed over a Spring managed SqlSession
- ViewDragHelper实现仿qq列表滑动删除
- android studio __android_log_print 问题
- 酒店管理系统_02-Servlet版本-mysql数据库(使用方法封装自动创建数据表)
- Bzoj4006:[JLOI2015]管道连接:斯坦纳树
- NOIP 2010 引水入城
- MyBatis集合Spring(二)之SqlSession
- iOS—数据缓存
- hihoCoder搜索二·骑士问题
- 烽火传递
- Java 集合系列10之 HashMap详细介绍(源码解析)和使用示例
- 酒店管理系统_03-Servlet版本-mysql数据库-插入数据
- redis
- smarty模版手册
- 网络安全及Web安全学习