spring管理hibernate session的问题探究
我们再用spring管理hibernate的时候, 我们会继承HibernateDaoSupport 或者HibernateTemplate类.
我们不知道这两个类之间有什么关系. 也没有去关闭session. 让我很是心不安,他可没有关闭session呀.如果..真的是后果不堪设想.百度了好久, 谷歌了好多. 都没有一个像样的说法. 说spring中HibernateDaoSupport会自己关闭session.
眼见为实.于是乎决定查看spring源码一探究竟.
先打开HibernateDaoSupoprt看看.
- public abstract class HibernateDaoSupport extends DaoSupport {
- private HibernateTemplate hibernateTemplate;
- public final void setSessionFactory(SessionFactory sessionFactory) {
- this.hibernateTemplate = createHibernateTemplate(sessionFactory);
- }
- protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
- return new HibernateTemplate(sessionFactory);
- }
- public final SessionFactory getSessionFactory() {
- return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
- }
- public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
- this.hibernateTemplate = hibernateTemplate;
- }
- public final HibernateTemplate getHibernateTemplate() {
- return hibernateTemplate;
- }
- protected final void checkDaoConfig() {
- if (this.hibernateTemplate == null) {
- throw new IllegalArgumentException("sessionFactory or hibernateTemplate is required");
- }
- }
- protected final Session getSession()
- throws DataAccessResourceFailureException, IllegalStateException {
- return getSession(this.hibernateTemplate.isAllowCreate());
- }
- protected final Session getSession(boolean allowCreate)
- throws DataAccessResourceFailureException, IllegalStateException {
- return (!allowCreate ?
- SessionFactoryUtils.getSession(getSessionFactory(), false) :
- SessionFactoryUtils.getSession(
- getSessionFactory(),
- this.hibernateTemplate.getEntityInterceptor(),
- this.hibernateTemplate.getJdbcExceptionTranslator()));
- }
- protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
- return this.hibernateTemplate.convertHibernateAccessException(ex);
- }
- protected final void releaseSession(Session session) {
- SessionFactoryUtils.releaseSession(session, getSessionFactory());
- }
在这里我们会注意到一个private 对象. 那就是HibernateTemplate. 这里面也有一个HibernateTemplate的set. get.
哦: 原来如此.呵呵,很白痴的事.
比如说. BaseDao extends HibernateDaoSupport 我们会super.getHibernateTemplate.find(hql);
super.getHibernateTemplate.save(obj);
和BaseDao extends HibernateTemplate 中super.find(hql)和super.save(obj);是等效的.
原来没有思考害的我改了一个多小时. 汗..
下面我们来看看HibernateTemplate是怎么样来操作session的呢.
照样我们贴出源代码. 由于这个类代码较多. 我只贴出来几个代表性的属性和方法, 供大家参考.
public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {
private boolean allowCreate = true;
private boolean alwaysUseNewSession = false;
private boolean exposeNativeSession = false;
private boolean checkWriteOperations = true;
private boolean cacheQueries = false;
private String queryCacheRegion;
private int fetchSize = 0;
private int maxResults = 0;
public void ......();
} 一系列的方法.
下面我们看看save()方法.
- public Serializable save(final Object entity) throws DataAccessException {
- return (Serializable) execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.save(entity);
- }
- }, true);
- }
我们再看看update(), merge(), find()等方法的源码.
- //update 方法
- public void update(Object entity) throws DataAccessException {
- update(entity, null);
- }
- public void update(final Object entity, final LockMode lockMode) throws DataAccessException {
- execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- session.update(entity);
- if (lockMode != null) {
- session.lock(entity, lockMode);
- }
- return null;
- }
- }, true);
- }
- //merge()
- public Object merge(final Object entity) throws DataAccessException {
- return execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.merge(entity);
- }
- }, true);
- }
- //find()
- public List find(String queryString) throws DataAccessException {
- return find(queryString, (Object[]) null);
- }
- public List find(String queryString, Object value) throws DataAccessException {
- return find(queryString, new Object[] {value});
- }
- public List find(final String queryString, final Object[] values) throws DataAccessException {
- return (List) execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query queryObject = session.createQuery(queryString);
- prepareQuery(queryObject);
- if (values != null) {
- for (int i = 0; i < values.length; i++) {
- queryObject.setParameter(i, values[i]);
- }
- }
- return queryObject.list();
- }
- }, true);
- }
细心的朋友们可能发现了. 他们无一例外的都调用了一个叫做execute()的方法. 对了. 我们再看看execute的面目.到底他干了一件什么样的事情呢?]
- public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
- Session session = getSession();
- boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory());
- if (existingTransaction) {
- logger.debug("Found thread-bound Session for HibernateTemplate");
- }
- FlushMode previousFlushMode = null;
- try {
- previousFlushMode = applyFlushMode(session, existingTransaction);
- enableFilters(session);
- Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session));
- Object result = action.doInHibernate(sessionToExpose);
- flushIfNecessary(session, existingTransaction);
- return result;
- }
- catch (HibernateException ex) {
- throw convertHibernateAccessException(ex);
- }
- catch (SQLException ex) {
- throw convertJdbcAccessException(ex);
- }
- catch (RuntimeException ex) {
- // Callback code threw application exception...
- throw ex;
- }
- finally {
- if (existingTransaction) {
- logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
- disableFilters(session);
- if (previousFlushMode != null) {
- session.setFlushMode(previousFlushMode);
- }
- }
- else {
- SessionFactoryUtils.releaseSession(session, getSessionFactory());
- }
- }
- }
抛掉其他的不管. finally中我们可以看到. 如果existingTransaction 他会
logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
他并没有立即关闭session.
否则
SessionFactoryUtils.releaseSession(session, getSessionFactory());
他释放掉了session . 真的close()了吗?
我们在看看sessionFactoryUtil.的releaseSession()
- public static void releaseSession(Session session, SessionFactory sessionFactory) {
- if (session == null) {
- return;
- }
- // Only close non-transactional Sessions.
- if (!isSessionTransactional(session, sessionFactory)) {
- closeSessionOrRegisterDeferredClose(session, sessionFactory);
- }
- }
- static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) {
- Map holderMap = (Map) deferredCloseHolder.get();
- if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) {
- logger.debug("Registering Hibernate Session for deferred close");
- Set sessions = (Set) holderMap.get(sessionFactory);
- sessions.add(session);
- if (!session.isConnected()) {
- // We're running against Hibernate 3.1 RC1, where Hibernate will
- // automatically disconnect the Session after a transaction.
- // We'll reconnect it here, as the Session is likely gonna be
- // used for lazy loading during an "open session in view" pase.
- session.reconnect();
- }
- }
- else {
- doClose(session);
- }
- }
- private static void doClose(Session session) {
- if (session != null) {
- logger.debug("Closing Hibernate Session");
- try {
- session.close();
- }
- catch (HibernateException ex) {
- logger.error("Could not close Hibernate Session", ex);
- }
- catch (RuntimeException ex) {
- logger.error("Unexpected exception on closing Hibernate Session", ex);
- }
- }
- }
spring管理hibernate session的问题探究的更多相关文章
- Spring管理Hibernate
为什么要用Hibernate框架? 既然用Hibernate框架访问管理持久层,那为何又提到用Spring来管理以及整合Hibernate呢? 首先我们来看一下Hibernate进行操作的步骤.比如添 ...
- ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存
ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存 hibernate : Hibernate是一个持久层框架,经常访问物理数据库 ...
- spring管理hibernate,mybatis,一级缓存失效原因
mybatis缓存:一级缓存和二级缓存 hibernate缓存:一级缓存和二级缓存 关于缓存: 缓存是介于物理数据源与应用程序之间,是对数据库中的数据复制一份临时放在内存中的容器, 其作用是为了减少应 ...
- Spring管理Hibernate事务
在没有加入Spring来管理Hibernate事务之前,Hibernate对事务的管理的顺序是: 开始事务 提交事务 关闭事务 这样做的原因是Hibernate对事务默认是手动提交,如果不想手动提交, ...
- Spring管理 hibernate 事务配置的五种方式
Spring配置文件中关于事务配置总是由三个组成部分,DataSource.TransactionManager和代理机制这三部分,无论是那种配置方法,一般变化的只是代理机制这块! 首先我创建了两个类 ...
- [转]利于ThreadLocal管理Hibernate Session
摘自http://aladdin.iteye.com/blog/40986 在利用Hibernate开发DAO模块时,我们和Session打的交道最多,所以如何合理的管理Session,避免Sessi ...
- Spring异常解决 java.lang.NullPointerException,配置spring管理hibernate时出错
@Repository public class SysUerCDAO { @Autowired private Hibernate_Credit hibernate_credit; /** * 根据 ...
- 关于spring管理hibernate事物
下面这篇文章对我帮助很大.http://blog.csdn.net/jianxin1009/article/details/9202907
- Spring对hibernate的事物管理
把Hibernate用到的数据源Datasource,Hibernate的SessionFactory实例,事务管理器HibernateTransactionManager,都交给Spring管理.一 ...
随机推荐
- Node.js中的express框架获取http参数
最近本人在学习开发NodeJs,使用到express框架,对于网上的学习资料甚少,因此本人会经常在开发中做一些总结. express获取参数有三种方法:官网介绍如下 Checks route para ...
- helm 安装 spinnaker
$ curl -Lo values.yaml https://raw.githubusercontent.com/kubernetes/charts/master/stable/spinnaker/v ...
- 服务级别协议(SLA)与运行水平协议(OLA)
服务级别协议(SLA)与运行水平协议(OLA): 服务级别管理和服务级别协议在国内已被广泛接受并成用.本文试图讨论服务级别协议(SLA)和运行水平协议(OLA)的异同. 1. SLA a.定义 服务级 ...
- jquery记录
jquery validate验证框架 参考:http://www.cnblogs.com/linjiqin/p/3431835.html http://www.runoob.com/jquery/j ...
- 关于Yii2.0的url路径优化问题(配置虚拟路径)
backend/config/main.php 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => fa ...
- spring定时任务执行两次的原因与解决方法
spring定时任务,本地执行一次,放到服务器上后,每次执行时会执行两次,原因及解决办法. http://blog.csdn.net/yaobengen/article/details/7031266 ...
- 解压*.tar.bz2的坑
下了一个压缩包,tar -xf 解压不了 解决办法: 装了bzip2工具 bzip2 -d **.tar.bz2 //将文件解压成**.tar tar -xf **.tar //解包 听说可以 tar ...
- mysql新建用户并授权
参考:https://www.cnblogs.com/zhangdiIT/p/8116776.html
- Weblogic的中的文件上传
在weblogic中在jsp页面中this.getServletContext().getRealPath("/upload")这样的写法是要报错的在jsp页面总你甚至不能使用th ...
- Shell 常用命令总结
Shell常用命令总结 1 ls命令:列出文件 ls -la 列出当前目录下的所有文件和文件夹 ls a* 列出当前目录下所有以a字母开头的文件 ls -l *.txt 列出当前目录下所有后缀名 ...