[已解决] org.hibernate.HibernateException:没有活动事务,get无效

Recently I was developing a simple hibernate application with version 4.3.5.Final and everything looked fine to me until I got below exception.

最近我正在开发一个简单的Hibernate应用程序,版本为4.3.5.Final ,一切对我来说都很好,直到出现异常为止。

org.hibernate.HibernateException: get is not valid without active transaction
	org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
	com.sun.proxy.$Proxy26.get(Unknown Source)

org.hibernate.HibernateException:如果没有活动的交易,get无效 (org.hibernate.HibernateException: get is not valid without active transaction)

The hibernate code snippet where the exception was getting thrown was:

引发异常的Hibernate代码段是:

Session session = sessionFactory.getCurrentSession();
//below line throws exception
Employee emp = (Employee) session.get(Employee.class, empId);

After some debugging I found out that we need to start the transaction to solve this problem. So I changed my above code snippet to;

经过一些调试后,我发现我们需要启动事务来解决此问题。 所以我将上面的代码片段更改为;

Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, empId);
tx.commit();

And the problem was gone and everything was working fine. Further reading: Hibernate Tutorial for Beginners

问题消失了,一切工作正常。 进一步阅读: 初学者的Hibernate教程

I hope this information will save someone else time in debugging the root cause of the issue.

我希望这些信息可以节省其他人调试问题根本原因的时间。

翻译自: https://www.journaldev.com/2900/org-hibernate-hibernateexception-get-not-valid-without-active-transaction

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值