org.hibernate.LazyInitializationException Solution


In this article, we are discussing about a hibernate exception i.e org.hibernate. LazyInitializationException along with a Solution to this Exception.

Exception StackTrace:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate.


Indicates access to unfetched data outside of a session context. For example, when an uninitialized proxy or collection is accessed after the session was closed.

Hibernate throws a LazyInitializationException if you try to access a not initialized relationship to another entity without an active session. You can see a simple example for this in the following code snippet.

EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Employee e = em.find(Author.class, 101); em.getTransaction().commit(); em.close(); System.out.print(e.getFirstName() + " " + e.getLastName() + " "+e.getId() + " ");


The most easy and popular way to do it is to access a relationship with 'FetchType.LAZY' in your client side which you did not initialize in your backend side.


Please, do not use the open session in view anti-pattern. It causes more harm then it provides benefits.

The best way to fix a LazyInitializationException is to initialize the required relationship in your backend (business) tier. But don't initialize all relationships just because there might be one client out there who needs one of them. For performance improvement, you should only initialize the relationships which you need.

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote


Get Programming Help

Play 2048 Game Online

Search Tags