The best way to handle the LazyInitializationException - Vlad Mihalcea
Introduction
The LazyInitializationExceptionis undoubtedly one of the most common exceptions you can get when using Hibernate. This article is going to summarize the best and the worst ways of handling lazy associations.
Fetching 101
With JPA, not only you can fetch entities from the database, but you can also fetch entity associations as well. For this reason, JPA defines two FetchTypestrategies:
-
EAGER -
LAZY
The problem with EAGER fetching
EAGERfetching means that associations are always retrieved along with their parent entity. In reality, EAGER fetching is very bad from a performance perspectivebecause it’s very difficult to come up with a global fetch policy that applies to every business use case you might have in your enterprise application.
Once you have an EAGERassociation, there is no way you can make it LAZY. This way, the association will always be fetched even if the user does not necessarily need it for a particular use case. Even worse, if you forget to specify that an EAGER association needs to be JOIN FETCH-ed by a JPQL query, Hibernate is going to issue a secondary select for every uninitialized association, leading to N+1 query problems.
Unfortunately, JPA 1.0 decided that @ManyToOneand @OneToOneshould default to FetchType.EAGER, so now you have to explicitly mark these two associations as FetchType.LAZY:
@ManyToOne(fetch = FetchType.LAZY) private Post post;
LAZY fetching
For this reason, it’s better to use LAZYassociations. A LAZYassociation is exposed via a Proxy, which allows the data access layer to load the association on demand. Unfortunately, LAZYassociations can lead to LazyInitializationException.
For our next example, we are going to use the following entities:
When executing the following logic:
List<PostComment> comments = null;
EntityManager entityManager = null;
EntityTransaction transaction = null;
try {
entityManager = entityManagerFactory()
.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
comments = entityManager.createQuery(
"select pc " +
"from PostComment pc " +
"where pc.review = :review", PostComment.class)
.setParameter("review", review)
.getResultList();
transaction.commit();
} catch (Throwable e) {
if (transaction != null &&
transaction.isActive())
transaction.rollback();
throw e;
} finally {
if (entityManager != null) {
entityManager.close();
}
}
try {
for(PostComment comment : comments) {
LOGGER.info(
"The post title is '{}'",
comment.getPost().getTitle()
);
}
} catch (LazyInitializationException expected) {
assertEquals(
"could not initialize proxy - no Session",
expected.getMessage()
);
} Hibernate is going to throw a LazyInitializationExceptionbecause the PostCommententity did not fetch the Postassociation while the EntityManagerwas still opened, and the Postrelationship was marked with FetchType.LAZY:
@ManyToOne(fetch = FetchType.LAZY) private Post post;
How NOT to handle LazyInitializationException
Unfortunately, there are also bad ways of handling the LazyInitializationExceptionlike:
These two Anti-Patterns are very inefficient from a database perspective, so you should never use them in your enterprise application.
JOIN FETCH to the rescue
Entities are only needed when the current running application-level transactionneeds to modify the entities that are being fetched. Because of the automatic dirty checking mechanism, Hibernate makes it very easy to translate entity state transitionsinto SQL statements.
Considering that we need to modify the PostCommententities, and we also need the Postentities as well, we just need to use the JOIN FETCHdirective like in the following query:
comments = entityManager.createQuery(
"select pc " +
"from PostComment pc " +
"join fetch pc.post " +
"where pc.review = :review", PostComment.class)
.setParameter("review", review)
.getResultList(); The JOIN FETCHdirective instructs Hibernate to issue an INNER JOIN so that Postentities are fetched along with the PostCommentrecords:
SELECT pc.id AS id1_1_0_ ,
p.id AS id1_0_1_ ,
pc.post_id AS post_id3_1_0_ ,
pc.review AS review2_1_0_ ,
p.title AS title2_0_1_
FROM post_comment pc
INNER JOIN post p ON pc.post_id = p.id
WHERE pc.review = 'Excellent!' That’s it! It’s as simple as that!
DTO projection to the rescue
Now, we are not done yet. What if you don’t even want entities in the first place. If you don’t need to modify the data that’s being read, why would you want to fetch an entity in the first place? A DTO projectionallows you to fetch fewer columns and you won’t risk any LazyInitializationException.
For instance, we can have the following DTO class:
public class PostCommentDTO {
private final Long id;
private final String review;
private final String title;
public PostCommentDTO(
Long id, String review, String title) {
this.id = id;
this.review = review;
this.title = title;
}
public Long getId() {
return id;
}
public String getReview() {
return review;
}
public String getTitle() {
return title;
}
} If the business logic only needs a projection, DTOs are much more suitable than entities. The previous query can be rewritten as follows:
List<PostCommentDTO> comments = doInJPA(entityManager -> {
return entityManager.createQuery(
"select new " +
" com.vladmihalcea.book.hpjp.hibernate.fetching.PostCommentDTO(" +
" pc.id, pc.review, p.title" +
" ) " +
"from PostComment pc " +
"join pc.post p " +
"where pc.review = :review", PostCommentDTO.class)
.setParameter("review", review)
.getResultList();
});
for(PostCommentDTO comment : comments) {
LOGGER.info("The post title is '{}'", comment.getTitle());
} And Hibernate can execute a SQL query which only needs to select threecolumns instead of five:
SELECT pc.id AS col_0_0_ ,
pc.review AS col_1_0_ ,
p.title AS col_2_0_
FROM post_comment pc
INNER JOIN post p ON pc.post_id = p.id
WHERE pc.review = 'Excellent!' Not only that we got rid of the LazyInitializationException, but the SQL query is even more efficient. Cool, right?
If you enjoyed this article, I bet you are going to love my Bookand Video Coursesas well.
Conclusion
LazyInitializationExceptionis a code smell because it might hide the fact that entities are used instead of DTO projections. Sometimes, fetching entities is the right choice, in which case, a JOIN FETCHdirective is the simplest and the best way to initialize the LAZYHibernate proxies.


