Spring框架学习[HibernateTemplate对Hibernate的封装](十二)
2014-11-24 03:05:48
·
作者:
·
浏览: 21
否需要新的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()); } } } }
(2).HibernateTemplate中增删改查操作的简单实现:
以查询为例,分析HibernateTemplate如何通过execute方法回调Hibernate相应的API,源码如下:
[java] view plaincopyprint //查询指定Id的实体 public Object get(String entityName, Serializable id) throws DataAccessException { return get(entityName, id, null); } //真正调用Hibernate API查询的方法 public Object get(final String entityName, final Serializable id, final LockMode lockMode) throws DataAccessException { //调用Hibernate本地查询方法,参数是一个实现HibernateCallback接口的 //匿名内部类,用于execute方法回调 return executeWithNativeSession(new HibernateCallback