[Solved] org.hibernate.HibernateException: get is not valid without active transaction With Examples

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.


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 is not valid without active transaction

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


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

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

By admin

Leave a Reply

%d bloggers like this: