Spring框架学习[HibernateTemplate对Hibernate的封装](十一)
2014-11-24 03:05:48
·
作者:
·
浏览: 30
的配置,然后设置Hibernate配置,最后生成SessionFactory的过程。 4.HibernateTemplate实现:
和Spring对jdbc封装类似,Spring使用HibernateTemplate对Hibernate也进行了一下API封装,通过execute回调来调用Hibernate的相关操作处理,接下来简单分析HibernateTemplate的核心实现。
(1). execute相关方法的实现:
与JdbcTemplate类似,execute相关方法也是HibernateTemplate的基础核心方法,在execute相关方法中,Spring提供获取Hibernate Session,为当前的Session进行事务处理等通用的操作,源码如下:
[java] view plaincopyprint //最基础的execute方法 public
T execute(HibernateCallback
action) throws DataAccessException { return doExecute(action, false, false); } //需要在新的Hibernate Session中执行的execute方法 public
T executeWithNewSession(HibernateCallback
action) { return doExecute(action, true, false); } //需要在Hibernate本地Session中执行的execute方法 public
T executeWithNativeSession(HibernateCallback
action) { return doExecute(action, false, true); } //真正调用Hibernate API的地方 protected
T doExecute(HibernateCallback
action, boolean enforceNewSession, boolean enforceNativeSession) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); //获取Hibernate会话,判断是否需要新的Session Session session = (enforceNewSession SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()) : getSession()); //是否存在事务 boolean existingTransaction = (!enforceNewSession && (!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory()))); if (existingTransaction) { logger.debug("Found thread-bound Session for HibernateTemplate"); } //刷新模式 FlushMode previousFlushMode = null; try { //根据Hibernate Session和事务类型应用相应的刷新模式 previousFlushMode = applyFlushMode(session, existingTransaction); //对Session开启过滤器 enableFilters(session); //判断Hibernate Session是否需要代理包装 Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() session : createSessionProxy(session)); //对HibernateCallBack中回调函数的调用,真正调用Hibernate API T result = action.doInHibernate(sessionToExpose); flushIfNecessary(session, existingTransaction); return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (SQLException ex) { throw convertJdbcAccessException(ex); } catch (RuntimeException ex) { throw ex; } finally { //如果存在事务,则调用完毕之后不关闭Session if (existingTransaction) { logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate"); //对Session禁用过滤器 disableFilters(session); if (previousFlushMode != null) { session.setFlushMode(previousFlushMode); } } //如果不存在事务,则关闭当前的Session else { if (isAlwaysUseNewSession()) { SessionFactoryUtils.closeSession(session); } else { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory()); } } } }