mybatis与hibernate常用的持久化类,及sqlsession和sqlsessionTemplate区别
首先, 通过翻阅源码,我们来整理一下mybatis进行持久化操作时重要的几个类:
SqlSessionFactoryBuilder:build方法创建SqlSessionFactory实例。
SqlSessionFactory:创建SqlSession实例的工厂。 SqlSession:用于执行持久化操作的对象,类似于jdbc中的Connection。
SqlSessionTemplate:MyBatis提供的持久层访问模板化的工具,线程安全,可通过构造参数或依赖注入SqlSessionFactory实例。 Hibernate是与MyBatis类似的orm框架,这里与Hibernate进行一下对比,Hibernate中对于connection的管理,是通过以下几个重要的类:
SessionFactory:创建Session实例的工厂,类似于MyBatis中的SqlSessionFactory。
Session:用来执行持久化操作的对象,类似于jdbc中的Connection。 HibernateTemplate:Hibernate提供的持久层访问模板化的工具,线程安全,可通过构造参数或依赖注入SessionFactory实例。 在日常的开发中,我们经常需要这样对MyBatis和Spring进行集成,把sqlSessionFactory交给Spring管理,通常情况下,我们这样配置:
? <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean> 通过上面的配置,Spring将自动创建一个SqlSessionFactory对象,其中使用到了org.mybatis.spring.SqlSessionFactoryBean,其 是MyBatis为Spring
提供的用于创建SqlSessionFactory的类,将在Spring应用程序的上下文建议一下可共享的 MyBatis SqlSessionFactory实例,我们可以通过依赖注入将
SqlSessionFactory传递给MyBatis的一些接口。 如果通过Spring进行事务的管理,我们需要增加Spring注解的事务管理机制,如下配置:
? <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <tx:annotation-driven/> 这样,我们就可以使用Spring @Transactional注解,进行事务的控制,表明所注释的方法应该在一个事务中运行。 Spring将在事务成功完成后提交事务,
在事务发生错误时进行异常回滚,而且,Spring会将产生的MyBatis异常转换成适当的 DataAccessExceptions,从而提供具体的异常信息。 下面,我们通过分析SqlSessionUtils中getSession的源码,来详细的了解一下sqlSession的产生过程,源码如下:
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) { notNull(sessionFactory, "No SqlSessionFactory specified");
notNull(executorType, "No ExecutorType specified"); SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory); if (holder != null && holder.isSynchronizedWithTransaction()) {
if (holder.getExecutorType() != executorType) {
throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction");
} holder.requested(); if (logger.isDebugEnabled()) {
logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
} return holder.getSqlSession();
} if (logger.isDebugEnabled()) {
logger.debug("Creating a new SqlSession");
} SqlSession session = sessionFactory.openSession(executorType); // Register session holder if synchronization is active (i.e. a Spring TX is active)
//
// Note: The DataSource used by the Environment should be synchronized with the
// transaction either through DataSourceTxMgr or another tx synchronization.
// Further assume that if an exception is thrown, whatever started the transaction will
// handle closing / rolling back the Connection associated with the SqlSession.
if (isSynchronizationActive()) {
Environment environment = sessionFactory.getConfiguration().getEnvironment(); if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
if (logger.isDebugEnabled()) {
logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
} holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
bindResource(sessionFactory, holder);
registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
holder.setSynchronizedWithTransaction(true);
holder.requested();
} else {
if (getResource(environment.getDataSource()) == null) {
if (logger.isDebugEnabled()) {
logger.debug("SqlSession [" + session + "] was not registered for synchronization because DataSource is not transactional");
}
} else {
throw new TransientDataAccessResourceException(
"SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active");
}
} return session;
} 上面的getSession方法,会从Spring的事务管理器中获取一个SqlSession或创建一个新的SqlSession,将试图从当前事务中得到一个SqlSession,然后,如果配置
有事务管理器的工厂并且Spring 的事务管理器是活跃的,它将会锁定当前事务的SqlSession,保证同步。主要是通过以下几个步骤进行SqlSession的创建:
它会首先获取SqlSessionHolder,SqlSessionHolder用于在TransactionSynchronizationManager中保持当前的SqlSession。
如果holder不为空,并且holder被事务锁定,则可以通过holder.getSqlSession()方法,从当前事务中获取sqlSession,即 Fetched SqlSession from current transaction。 如果不存在holder或没有被事务锁定,则会创建新的sqlSession,即 Creating a new SqlSession,通过sessionFactory.openSession()方法。 如果当前线程的事务是活跃的,将会为SqlSession注册事务同步,即 Registering transaction synchronization for SqlSession。
mybatis与hibernate常用的持久化类,及sqlsession和sqlsessionTemplate区别的更多相关文章
- 初识Hibernate之理解持久化类
上一篇文章我们简单介绍了Hibernate相关的一些最基本的文件及其作用,并在最后完整的搭建了Hibernate的运行环境,成功的完成了与数据库的映射.但是至于其中的一些更加细节的地方并没有 ...
- Hibernate中的持久化类
一.持久化类概述 就是一个JavaBean,这个JavaBean与表建立了映射关系.这个类就称为是持久化类. 简单理解为 持久化类=JavaBean+映射文件. 持久化类:是指其实例需要被Hibern ...
- [原创]java WEB学习笔记77:Hibernate学习之路---Hibernate 版本 helloword 与 解析,.环境搭建,hibernate.cfg.xml文件及参数说明,持久化类,对象-关系映射文件.hbm.xml,Hibernate API (Configuration 类,SessionFactory 接口,Session 接口,Transaction(事务))
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- 三、hibernate中持久化类的使用
hibernate的持久化类 持久化:将内存中的一个对象持久化到数据库中的过程,hibernate就是一个用来进行持久化的框架 持久化类:一个Java对象与数据库中表建立了关系映射,那么这个类在hib ...
- Hibernate学习——持久化类的学习
A.概念 持久化:将内存中的对象持久化(存储)到数据库的过程.Hibernate就是持久化的框架. 持久化类:一个普通java对象与数据库的表建立了映射关系,那么这个类在Hiberna中被称为持久化类 ...
- Hibernate中持久化类与持久化对象
1.JavaBean类 JavaBean类是实体类,必须一下属性,private修饰的成员属性,public修饰的getter与setter访问方法,public修饰的空参构造器,实现Serializ ...
- 三大框架 之 Hibernate生成策略与缓存策略(主键生成策略、持久化、持久化类划分、一级缓存、事物管理)
目录 Hibernate生成策略与缓存策略 主键生成策略 主键分类 主键的生成策略 持久化 什么是持久化 什么是持久化类 持久化类编写规则 持久化类的划分 三种状态区分 持久态对象特征 一级缓存 什么 ...
- JEECG Hibernate 自动更新 持久化
Hibernate不调用update却自动更新 - 七郎 - 博客园http://www.cnblogs.com/yangy608/p/4073941.html hibernate自动更新持久化类的问 ...
- Hibernate持久化类规则
注意事项: 提供无参的构造方法,因为在hibernate需要使用反射生成类的实例 提供私有属性,并对这些属性提供公共的setting和getting方法,因为在hibernate底层会将查询到的数据进 ...
随机推荐
- dedecms调用当前栏目的子栏目怎么操作
有时我们建网站会建很多分类,每个分类又有小分类,为了让顶级栏目获得更好的权重和排名,我们会聚合子栏目.那么dedecms调用当前栏目的子栏目怎么操作呢? 有两种方法:标签dede:sonchannel ...
- [py模块]random&string取随机字符串
栗子 - 取n位的随机字符串(大小写/数字) def get_random_str(len_str): import string import random letters_nums = strin ...
- hdu1305Immediate Decodability(字典树)
这题看是否 这题能A是侥幸,解决的办法是先存一下输入的字符串,进行排序. Problem Description An encoding of a set of symbols is said to ...
- docker:搭建lamp应用
(原文http://blog.csdn.net/smallfish1983/article/details/40108999?utm_source=tuicool) LAMP 指的 Linux(操作系 ...
- Intermediate Python for Data Science learning 1 - Basic plots with matplotlib
Basic plots with matplotlib from:https://campus.datacamp.com/courses/intermediate-python-for-data-sc ...
- MyBatis学习笔记(八)——Mybatis3.x与Spring4.x整合
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn arc ...
- 查看firefox浏览器 驱动geckodriver.exe文件的版本号的方法,以及下载链接
1-进入到geckodriver.exe文件的目录: 2-在路径栏下输入cmd: 3-命令行界面下输入:geckodriver.exe -h 可以看到文件的帮助信息,其中第一行就列出了版本号 为0.1 ...
- Python-sys模块,异常
习题1:题目:给一个不多于5位的正整数,要求:一.求它是几位数,二.逆序打印出各位数字. #encoding=utf-8 while True: try: num=int(raw_input(&quo ...
- linux服务器管理员的12个有用的命令
ifconfig: 在修改内核中已有的网络接口时,你会用到ifconfig命令.这个命令通常用于系统调校和调试,但同时也可以用于在启动过程中设置接口. netstat: 对于Linux用户来说这是一个 ...
- Rapid 2D-to-3D conversion——快速2D到3D转换
https://blog.csdn.net/qq_33445835/article/details/80143598 目前想做一个关于2D转3D的项目,由于国内资料比较少而且大部分都是基于国外的研究 ...