Spring框架学习[HibernateTemplate对Hibernate的封装](十三)

2014-11-24 03:05:48 · 作者: · 浏览: 25
e管理Session:

在4分析HibernateTemplate的doExecute法源码时我们看到,Spring根据是否需要新Session的判断,使用getSession和getNewSession两种不同的获取Session的方法,Spring中通过SessionFactoryUtils来管理HibernateSession,分析SessionFactoryUtils管理Session的实现源码:

(1).getNewSession实现:

[java] view plaincopyprint //获取新Session public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) { Assert.notNull(sessionFactory, "No SessionFactory specified"); try { //获取事务管理器中的sessionFactory线程局部变量 SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); //如果当前线程绑定了SessionFactory资源 if (sessionHolder != null && !sessionHolder.isEmpty()) { //如果有实体拦截器,则打开一个有实体拦截器的Session连接 if (entityInterceptor != null) { return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor); } //如果没有实体拦截器,则直接打开当前线程中绑定的Session连接 else { return sessionFactory.openSession(sessionHolder.getAnySession().connection()); } } //如果当前线程没有绑定SessionFactory资源 else { //如果有实体拦截器 if (entityInterceptor != null) { //打开一个包含给定实体拦截器的Session return sessionFactory.openSession(entityInterceptor); } //如果没有实体拦截器,则直接打开一个新的Session else { return sessionFactory.openSession(); } } } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }

(2).getSession实现:

[java] view plaincopyprint //获取Hibernate Session的入口方法 public static Session getSession(SessionFactory sessionFactory, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { try { //通过调用doGetSession来获取Hibernate Session return doGetSession(sessionFactory, null, null, allowCreate); } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } } //获取Hibernate Session private static Session doGetSession( SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws HibernateException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionF