HibernateException: No Hibernate Session bound to thread

本文解析了在使用SessionFactory.getCurrentSession执行Hibernate操作时出现的异常原因及解决办法。强调了Hibernate操作需包含在transaction中,并建议将事务管理配置在Service层。

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

异常栈:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
	at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
	at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:622)
	at org.springside.modules.orm.hibernate.SimpleHibernateDao.getSession(SimpleHibernateDao.java:90)
	at org.springside.modules.orm.hibernate.SimpleHibernateDao.createCriteria(SimpleHibernateDao.java:284)
	at org.springside.modules.orm.hibernate.SimpleHibernateDao.findUniqueBy(SimpleHibernateDao.java:165)

使用SessionFactory.getCurrentSession执行hibernate操作时,hibernate的操作默认必须包含在一个transaction中,也就是开始要用session.begionTransaction得到一个transaction 实例(譬如tx), 操作结束时在这个实例上进行事务的提交tx.commit或回滚tx.rollback. 如果这些CRUD操作不被包括在一个具体的transaction中,hibernate就会抛出上述异常。

在实际的SSH web应用开发中,我们通常用spring来进行事务的管理。我们一般不会在dao层使用transaction,事务被配置在service层上更为合理,因为业务层方法表示逻辑上的一个原子操作。在这种环境下,如果你遇到上述异常,请考虑一下service层上没有配置transaction,transaction有没有打开!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值