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.

6 comments:
very nice
thanks
You're welcome! :)
Also consider the Open Session in View pattern.
Hi Mike,
indeed Open Session in View pattern is great for any web applications. You can avoid LazyInitializationExceptions as a whole. Thanks for sharing this!
Anyway, consider to use JOIN FETCH to avoid the N+1 SELECT problem. JOIN FETCH is one possibility to reduce the number of database queries and therefore improve performance.
Is there any way to issue HQL query, that loads 1st level entities (customer in your example) and let Hibernate to use subselects (not join) to fetch the collections?
Nice, but i am new to JPA and having one doubt that, if our parent Entity having more than one Entities having this kind of relationship then the same ting (fetch join) we needs to do in the same HQL.
And if yes then is that will cause any performance issue in application.
Please let me know.
Thanks & Reg
Surendra.
Post a Comment