ITeye博客

org.hibernate.HibernateException: No Session found for current thread

tojaoomy · 2012-04-01 19:40 · Hibernate · 开源软件 · Markdown

Spring3.1.1 Intergrate with Hibernate 4.0.1 occurs the

 

org.hibernate.HibernateException: No Session found for current thread

 

In the applicationContext.xml configuration:

 

this configuration should like this

 

<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true" propagation="REQUIRED"/>
			<tx:method name="*" propagation="REQUIRED"/>
		</tx:attributes>
</tx:advice>

 

it seems that propagation set values[SUPPORTS|NOT_SUPPORTED|NEVER] will issue

 

No Session found for the current thread

评论(1)

  1. #1 楼 · jinnianshilongnian · 2012-04-02 14:13

    这个问题 在我的这篇帖子中提到过http://www.iteye.com/topic/1120924

    补充spring3.1.1源代码分析当 传播行为为 Support时报 org.hibernate.HibernateException: No Session found for current thread 异常:

    spring3.1开始 不提供(没有这个东西了)Hibernate4的 DaoSupport和Template,,而是直接使用原生的Hibernate4 API

    如在 Hibernate3中 HibernateTemplate中有如下代码 Java代码
    protected Session getSession() {
    if (isAlwaysUseNewSession()) {
    return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
    }
    else if (isAllowCreate()) {//默认是true,也就是即使你的传播行为是Supports也一定会有session存在的
    return SessionFactoryUtils.getSession(
    getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
    }
    else if (SessionFactoryUtils.hasTransactionalSession(getSessionFactory())) {
    return SessionFactoryUtils.getSession(getSessionFactory(), false);
    }
    else {
    try {
    return getSessionFactory().getCurrentSession();
    }
    catch (HibernateException ex) {
    throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);
    }
    }
    }

    但我们使用的是Hibernate4原生API,使用SpringSessionContext获取session,而这个isAllowCreate选项默认为false

    Java代码
    /**

    • Retrieve the Spring-managed Session for the current thread, if any. */
      public Session currentSession() throws HibernateException {
      try {
      return (org.hibernate.classic.Session) SessionFactoryUtils.doGetSession(this.sessionFactory, false);//最后的false即是
      }
      catch (IllegalStateException ex) {
      throw new HibernateException(ex.getMessage());
      }
      }

    SessionFactoryUtils类 Java代码
    public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate)
    throws HibernateException, IllegalStateException {

    return doGetSession(sessionFactory, null, null, allowCreate);  
    

    }

    可否认为这是集成Hibernate4的bug,或者采用OpenSessionInView模式解决或者传播行为最低为Required。

评论功能维护中,当前仅展示历史评论。