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.
我希望这些信息可以节省其他人调试问题根本原因的时间。