`

怪异的 No Hibernate Session bound to Thread !异常

阅读更多

java .lang .IllegalStateException: No Hibernate Session bound to thread , and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SessionFactoryUtils.doGetSession(SessionFactoryUtils.java :350)
at org.springframework.orm.hibernate3.SessionFactoryUtils.getSession(SessionFactoryUtils.java :200)
at com.sea.user.dao.BaseDAO.getSession(BaseDAO.java :23)
at com.sea.user.dao.impl.UserDAO.saveUser(UserDAO.java :16)
at com.sea.user.service.impl.UserService.saveUser(UserService.java :14)
at com.sea.user.action.UserAction.register(UserAction.java :48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java :39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java :25)

====================

意思是说你没有事务,无法产生Session与当前线程绑定,这通常是getHibernateTemplate() getSession()产生的问题,does not allow creation of non-transactional one here 不允许创建非事务,看过一些别人的见解,是说这里的Session必须和事务关联才能产生,(然后绑定到线程,进而在事务处理过程中Session只是唯 一的,这是我想的,保证在一次操作中是事务性的,Session(即一个连接唯一 )才可能,)而用HibernateCallback()就不会出现问题,然而很多人可能直接在Service里想得到 Session.

==================

reference to link:

https://forums.hibernate.org/viewtopic.php?p=2400339&sid=981dbe2a38a5e3a8b031bdbb8edde389

http://www.iteye.com/problems/33765

============================

 Spring的 getHibernateTemplate().getSessionFactory().getCurrentSession()的意思是得到当前线程 绑定的session,而当前线程绑定的session是通过当前的事务产生的,如果没有配置事务的话,当前线程threadlocal中就不存在 session,这样就出现no session错误。

而execute的回调方法,看源码HibernateTemplate中写道

public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");

    Session session = getSession();
    boolean existingTransaction = (!isAlwaysUseNewSession() &&
        (!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory())));


其中getSession,代码如下

protected Session getSession() {
    if (isAlwaysUseNewSession()) {
        return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
    }
    else if (isAllowCreate()) {
        return SessionFactoryUtils.getSession(
        getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
    }
    else {
        try {
            return getSessionFactory().getCurrentSession();
        }
        catch (HibernateException ex) {
            throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);
        }
    }


        其中默认private boolean alwaysUseNewSession = false,所以代码会走到else if (isAllowCreate())
注 意这里:else if (isAllowCreate()),其中在HibernateTemplate类中默认private boolean allowCreate = true;其实通过函数名字就很清楚。意思说如果当前线程中的session不存在的话,是否允许创建,而默认是允许的,接下来是创建当前线程中的 session的代码,所以在没有事务的状态下,用execute回调方法,就不会出现上述问题。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics