No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional

本文详细解析了SessionFactory.getCurrentSession()方法的工作原理,包括其如何获取当前线程中的Session,以及在不同情况下(如存在或不存在事务)的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

而execute方法,看源码HibernateTemplate中写道
Java code
?
1
2
3
4
5
6
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,代码如下
Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
            }
        }
    }


注意这里:else if (isAllowCreate()),其中在HibernateTemplate类中默认private boolean allowCreate = true;

意思说如果当前线程中的session不存在的话,是否允许创建,而默认是允许的,通过函数名字就很清楚,接下来是创建当前线程中的session的代码。


http://bbs.youkuaiyun.com/topics/280063179


1: @Transactional声明的方法执行时,Spring的TransactionManager会自动Open Sesion,自动开启事务,并且将此Sesion绑定到SpringSessionContext(实际上是TransactionSynchronizationManager的ThreadLocal的Map)中..

 

2:SessionFactory.getCurrentSession()方法执行时,调用SpringSessionContext.currentSession()从TransactionSynchronizationManager的上下文中查找 当前的Session

 

3:找到后返回当前的Session,找不到,则返回HibernateException("No Sessionfound for current thread")



PS: 从中,我们也知道了,执行SessionFactoryImpl.openSession()时,只是简单地new 一个SessionBuilder,然后调用SessionBuilder.openSession(),得到的Session是不会绑定到任何 org.hibernate.context.spi.CurrentSessionContext 在上下文中的.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值