Prevent Hibernate LazyInitializationException


Did you ever have to bother with LazyInitializationExceptions in Hibernate? I'm sure you have. :) This famous exception occurs if you try to access any non-initialized assocation (or proxy) when the assigned hibernate session has already been closed. There are many solutions for this problem, e.g. fetching the association directly via the hibernate query language. Think about a hibernate mapped entity Customer which has a one-to-many relation to an Order entity. Both classes are mapped to different database tables with a foreign key constraint.

The following HQL query not only will select all customers from the database, in addition it will directly fetch all orders related to these customers:

select distinct c from Customer c left join fetch c.orders;

Executing the HQL results in one SQL SELECT. No further selects are executed on accessing the customers orders. So no LazyInitializationException will ever be thrown if the hibernate session is closed already.

On the other side you have to pay attention when using JOIN FETCH in combination with pagination (see Query#setFirstResult() and setMaxResults()). Hibernate isn't able to perform pagination on database-level while using JOIN FETCH. This issue is related to the fact that JOIN FETCH sql statements return multiple rows for the same entity. Therefor pagination will be performed in-memory which can result in bad database performance.

Benjamin is Software Engineer, Full Stack Developer at Pondus, an excited runner and table foosball player. Get in touch on Twitter and GitHub.

Do you know Sequency?

Read More