The best way to handle the LazyInitializationException

Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn’t that be just awesome?

Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.

So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night!


The LazyInitializationException is 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 FetchType strategies:

  • LAZY

The problem with EAGER fetching

EAGER fetching means that associations are always retrieved along with their parent entity. In reality, EAGER fetching is very bad from a performance perspective because 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 EAGER association, 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 @ManyToOne and @OneToOne should 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 LAZY associations. A LAZY association is exposed via a Proxy, which allows the data access layer to load the association on demand. Unfortunately, LAZY associations 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()
    transaction = entityManager.getTransaction();

    comments = entityManager.createQuery(
        "select pc " +
        "from PostComment pc " +
        "where = :review", PostComment.class)
    .setParameter("review", review)

} catch (Throwable e) {
    if (transaction != null && 
    throw e;
} finally {
    if (entityManager != null) {

try {
    for(PostComment comment : comments) {
            "The post title is '{}'", 
} catch (LazyInitializationException expected) {
        "could not initialize proxy - no Session", 

Hibernate is going to throw a LazyInitializationException because the PostComment entity did not fetch the Post association while the EntityManager was still opened, and the Post relationship 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 LazyInitializationException like:

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 transaction needs to modify the entities that are being fetched. Because of the automatic dirty checking mechanism, Hibernate makes it very easy to translate entity state transitions into SQL statements.

Considering that we need to modify the PostComment entities, and we also need the Post entities as well, we just need to use the JOIN FETCH directive like in the following query:

comments = entityManager.createQuery(
    "select pc " +
    "from PostComment pc " +
    "join fetch " +
    "where = :review", PostComment.class)
.setParameter("review", review)

The JOIN FETCH directive instructs Hibernate to issue an INNER JOIN so that Post entities are fetched along with the PostComment records:

SELECT AS id1_1_0_ , AS id1_0_1_ ,
       pc.post_id AS post_id3_1_0_ , AS review2_1_0_ ,
       p.title AS title2_0_1_
FROM   post_comment pc
INNER JOIN post p ON pc.post_id =
WHERE = '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 projection allows 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) { = id; = 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 " +
        "" +
        ",, p.title" +
        "   ) " +
        "from PostComment pc " +
        "join p " +
        "where = :review", PostCommentDTO.class)
    .setParameter("review", review)

for(PostCommentDTO comment : comments) {"The post title is '{}'", comment.getTitle());

And Hibernate can execute a SQL query which only needs to select three columns instead of five:

SELECT AS col_0_0_ , AS col_1_0_ ,
       p.title AS col_2_0_
FROM   post_comment pc
INNER JOIN post p ON pc.post_id =
WHERE = '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 Book and Video Courses as well.


LazyInitializationException is 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 FETCH directive is the simplest and the best way to initialize the LAZY Hibernate proxies.

Transactions and Concurrency Control eBook

4 Comments on “The best way to handle the LazyInitializationException

  1. Ok but how to do multiple nested fetch?

    Like a

    Editor has a one to many relation to Person and person has a Many to many relation to PersonActivities?

    tried with 2 fetch, and both have 2 set and get failed to lazily initialize a collection of role

  2. Hello Vlad, your blog about about DTOs projection is really useful. I am curious if it is suitable and brings any value in case we need to expose all the columns from the database. I mean, does DTOs projection bring any value in terms of performance in case it is used to select all the columns from the database?

    • Thanks. Using DTOs allows you to mark down exactly the properties that are needed. Using an entity does not because, in time, the entity will get more and more properties, even associations. So, what started as a view that fetched 5 properties, it’s now a view that fetched 15 properties, among which some can be JSON columns containing large values.

      So, yes, using DTOs can bring value even when when you need to select all the current columns of a table, but not all the columns the table will have in the future.

Leave a Reply

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.