Hibernate Tips: How to initialize lazy relationships within a query

By Thorben Janssen

Association Mapping, Jpql, Query

Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

How can I initialize a lazy relationship within a query to avoid LazyInitializationExceptions?

Solution:

Hibernate throws a LazyInitializationException if you try to use the attribute of a lazily fetched relationship outside of an active Hibernate Session.

You can avoid that by initializing the relationship before you close the session. Hibernate and JPA support different ways to do that. The easiest one is a JOIN FETCH statement within a query, like the one in the following code snippet.

The additional FETCH  keyword tells Hibernate to not only join the entity for the query but also to fetch it from the database to initialize the attribute. This prevents LazyInitializationExceptions if you access the relationship attribute outside of an active Hibernate Session.

Learn more:

Join Fetch statements are only 1 option to initialize lazy relationships. Other interesting options are @NamedEntityGraphs and dynamic entity graphs which allow you to define a query independent graph of entities which shall be fetched with a query.

Initializing a required lazy relationship does not only prevent LazyInitializationExceptions, it also can improve the performance by avoiding n+1 select issues. I get into more details about that in this free mini-course and in the Hibernate Performance Tuning Online Training.
 

Hibernate Tips Book


Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.

Get it now as a paperback, ebook or PDF.


Tags

Association Mapping, Jpql, Query


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Repl​​​​​y

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}