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

Filed Under: Hibernate

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.

Comments

  1. Swadheen Mishra says:

    you have specified difference between save and persist that save can work outside transaction boundary and you have not activated transaction in your example so it was giving same exception in that case also ,can you clear the things

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages