The best way to handle the LazyInitializationException

(Last Updated On: January 29, 2018)

Introduction

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:

  • EAGER
  • 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:

postpostcommentlazyinitializationexception

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 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 pc.post " +
    "where pc.review = :review", PostComment.class)
.setParameter("review", review)
.getResultList();

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

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 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) {
        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 three columns 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 Book and Video Courses as well.

Conclusion

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.

Subscribe to our Newsletter

* indicates required
10 000 readers have found this blog worth following!

If you subscribe to my newsletter, you'll get:
  • A free sample of my Video Course about running Integration tests at warp-speed using Docker and tmpfs
  • 3 chapters from my book, High-Performance Java Persistence, 
  • a 10% discount coupon for my book. 
Get the most out of your persistence layer!

Advertisements

46 thoughts on “The best way to handle the LazyInitializationException

  1. Vlad, maybe I didn’t get what you are taking about Entity Graph, what’s the issue? Why Entity Graph is evil? Could you clarify or give me an example? But to be honest, I am working with Hibernate and many other developers and what I can say according to my experience:

    There’s no issue in writing two queries that are similar because they target two different business cases, and you also have integration tests for both of them

    Developers don’t like writing integration tests and sometimes they don’t do it, unfortunately. Developers really like to copy paste already written code. For instance: There is a repository method findAllClients: “select c from Client c join fetch c.accounts where c.age > 10 and a.amount > 1000 and bla bla bla”. In this case I really need to fetch accounts with client as well. But what happen if some developer needs to use this method (to get clients according to those restrictions – age >10 and amount > 1000 and so on), but they don’t need accounts. They just reuse this method and they don’t care that redundant data will be retrieved. It’s much easier and faster just to reuse it and you don’t need to create another one, almost the same method, without fetch c.accounts.
    Entity Graph gives the functionality to reuse query without fetch plan, and you can manage fetch plan in runtime, on query side.

    you don’t have to worry that modifying an entity property name will not be reflected in all queries

    Entity graph is placed on entity, it’s easy as abc to change field name because you are in the entity. But from join fetch side it’s not so easy.

    Which one is easier to understand: a JPQL query or a query that has a Graph which is also built with nested subgraphs and all

    Entity Graph is just responsible for fetch plan, what will be fetched, not for business part.

    In many situations, you don;t even need to fetch entities because DTO projections are more efficient.

    It’s an obvious. But sometimes I need entities.

    Which one is easier to understand: a JPQL query or a query that has a Graph which is also built with nested subgraphs and all?

    I don’t see any troubles to understand query cause as I’ve already mentioned entity graph just shows what will be retrieved.
    For instance:

    private TypedQuery findAdultClientsQuery() {
    return em.createQuery(“select c from Client c ” +
    “where c.age >= :age”, Client.class)
    .setParameter(“age”, 18);
    }

    public List<Client> findAdultClients() {
        return findAdultClientsQuery().getResultList();
    }
    
    public List<Client> findAdultClientsFetchAccounts() {
        return findAdultClientsQuery()
                .setHint(QueryHints.FETCHGRAPH, em.getEntityGraph(Client.ACCOUNTS_GRAPH))
                .getResultList();
    }
    

    If I need to figure out what my query does I just need to open findAdultClientsQuery method and I can get all information about query.

    I am using JPA 2.1 standard Entity Graph to avoid LazyInitException and N+1 issues and join fetch for Hibernate related cases, if I wanna use ScrollableResults for instance, cause ScrollableResults is a Hibernate feature, not JPA standard.

    Is it evil for you that Entity Graph hides additional joins, am I right?

    1. The last phrase captures exactly what I meant. I didn’t say that Entity Graphs are evil. I said that they make it less obvious of what JOINs or secondary selects are going to be executed.

      In my experience, I try to follow the Principle of least astonishment. The less magic, the better.

      BTW: Integration tests are not optional whether developers like it or not. You need to add that into your Definition of Done as well as a Peer Review phase. If one developer skips adding integration tests, the Peer Review process should reopen the issue so that tests are added.

      More, you can even use the actual DB and run it almost as fast as any in-memory database.

  2. Why not plain SQL?

    comments = jdbcTemplate.query(
    “SELECT pc.id, pc.review, p.title FROM post_comment pc INNER JOIN post p ON pc.post_id = p.id WHERE pc.review = ?”, (rs, rowNum) -> {
    return new PostCommentDTO(rs.getLong(1), rs.getString(2), rs.getString(3));
    }, “Excellent!”);

    You have improved readability, you don’t need to check the query stmt generated by HBN, the DTO doesn’t need a constructor with all required fields, …

    1. Because Hibernate can offer pagination even for native SQL statements without having to worry of the right DB syntax (especially on pre-12 Oracle). Does jdbcTample offer that for you too?

  3. Great article, Vlad.

    Although I understand the cons and risks of using Open Session In View (OSIV), normally I use it in most of applications I work on. OSIV works very well in the begining of a project where usually a team is developing only CRUDs and simple reports. This strategy brings a reasonable productivity, specially if your team doesn’t have good experience with Hibernate. [yeah, I know the best approach to solve this is training the team].

    But it’s very important understand this trade-off and knowing the moment when using join fecht and/or DTO projections. As you well said, they’re the best way to avoid performance issues in queries.

    By the way, I don’t like Entity Graphs due to its readability. JPQL for static queries and Criteria API for dynamic ones work like a charm, mainly if you write integration tests.

    1. The way OSIV speeds up development is just Technical Debt. It gives the illusion that the team is very Agile, and it can deliver a lot of features, but in reality, it pays in terms of architecture, layering, and ultimately performance. Just like you said, a training is cheaper and more reasonable than burying the project in Technical Debt.

    2. Hi Rafael,

      You’ve probably seen some of the bad uses of EntityGraphs (where people have gone crazy with annotations), but using them in Spring Data JPA the look really neat to me.
      Example:

      public interface ComponentRepository extends CrudRepository<Component, Long> {
      @EntityGraph(attributePaths = {“i18n”}, type=EntityGraphType.LOAD)
      Slice findAllByI18nPrimaryKeyLanguage(String language, Pageable pageable);
      }

      Here I have an explicitly specified query where attribute i18n (set as OneToMany-LAZY) is being initialised only on this call.
      For other implicit queries (like findAll(…) ) i18n is not being initialised.

      No JPQL, no Criteria API – just simple code for simple cases.
      Obviously for not-so-simple cases they may not work well, but then I’m still free to use a different mechanism for such cases.

      1. Now I undestand your point. Spring Data makes Entity Graph more useful than using it with Hibernate.

        And you’re right, @EntityGraph and @NamedQueries are the kind of things I don’t like due to the flood of annotations. I prefer to have all query details inside persistence layer.

    1. The Extended Persistence Context is meant to provide application-level transactions and workflows. As long as you attach it to a database connection, you will not get a LazyInitializationException. However, it has a different purpose than being a solution for the LazyInitializationException.

    1. Personally, I find that Entity Graph is just a superfluous addition to JPA. Why would I ever want to use a clumsy API when all I need is a JOIN FETCH directive. Nothing beats the JPQL expressiveness. While Criteria API makes sense for building dynamic queries, Entity Graphs make no sense at all.

      1. In my opinion Entity Graph is much better than join fetch.
        What would you do in this situation? :
        1. I need to fetch all adult clients with his accounts – “select c from Client c join fetch c.accounts where c.age >= 18”.
        2. I need to fetch all adults client without accounts. With join fetch I have two solutions:
        a.) create almost the same query just without join fetch, that’s not so good, it breaks maintainability cause if my query need to be changed I have to change 2 queries(with join fetch and without). Here is a simple example, but in real life it’s more likely that you have the complex query or if I need to fetch another child objects, for instance “select c from Client c join fetch c.passport where c.age>=18”, in this case I will have 3 queries.
        b.) split the query and use String concatenation, it looks ugly.

        But if you are using Entity Graph you can control fetch strategy on query side and you need to have just one query:
        String findAdultClientsQuery = “select c from Client c where c.age>=18”;
        1. em.createQuery(findAdultClientsQuery).getResultList();
        2. a.) em.createQuery(findAdultClientsQuery)
        .setHint(QueryHints.FETCHGRAPH, em.getEntityGraph(“ClientFetchAccounts”))
        .getResultList();
        and if you wanna fetch clients with passport:
        em.createQuery(findAdultClientsQuery)
        .setHint(QueryHints.FETCHGRAPH, em.getEntityGraph(“ClientFetchPassport”))
        .getResultList();

        You can manage fetch strategy in runtime on query side, it’s awesome, isn’t it?

      2. Since we’re talking about maintainability, doesn’t expressiveness counts for maintainability too? There’s no issue in writing two queries that are similar because they target two different business cases, and you also have integration tests for both of them. Because you have integration tests, you don’t have to worry that modifying an entity property name will not be reflected in all queries.

        The problem with Entity Graphs is that it gives you the impression that you are really gaining a lot from reusing one query in many situations, right? Well, entity queries are useful when you want to change data and you usually have more use cases when you just need a projection instead. In many situations, you don;t even need to fetch entities because DTO projections are more efficient. In the other use cases, you can use entity queries, and since JPQL is closer to SQL, you can make sure that the next developer will have an easy time figuring out what you wanted to query. Which one is easier to understand: a JPQL query or a query that has a Graph which is also built with nested subgraphs and all?

        More, a JPQL query is very predictable in terms of the actual SQL being executed. Criteria API and Entity Graphs are not so obvious, so you have to log every statement for every entity graph combination and make sure that the underlying SQL query is as efficient as it would be if you wrote it with JOQL.

        For all these reasons, I’ll always choose JPQL for non-dynamic entity queries.

      3. I had a similar experience with Igor on this.
        Using Spring Data JPA, I can have a repository layer supporting several queries on the same entity where each query can initialise a different set of LAZY properties. This works particularly well for entities that have LAZY relationships which have further LAZY relationships.
        So, even though the Entity Graph annotation can potentially get crazy, by keeping them simple I’m getting quite a lot of benefit without having to resort to JPQL (just to handle LAZY exceptions) or extra projection DTOs.
        To make it clear, I’m not saying that the way of solving it as shown in this article is not correct – only that I also find another way quite convenient and very straight forward.

      4. I understand why you find Entity Graphs very appealing, especially from an application developer perspective. However, have you checked the generated SQL queries? Is the number of queries optimal? Is the number of joins efficient as well?

        There are many ways to fetch data using Hibernate. Some techniques are efficient, while others are not very optimal. Enterprise applications are built to last. On the long run, will it matter that you spent one or two extra hours to make sure that the executed queries are as efficient as possible? You’ll rarely run into performance problems on a development machine. Usually, you’ll develop a feature, then you’ll deploy it, only to realize that after months of accumulating data, some queries become slower and slower.

      5. I agree with your second paragraph:
        “There are many ways to fetch data using Hibernate. Some techniques are efficient, while others are not very optimal. Enterprise applications are built to last. On the long run, will it matter that you spent one or two extra hours to make sure that the executed queries are as efficient as possible? You’ll rarely run into performance problems on a development machine. Usually, you’ll develop a feature, then you’ll deploy it, only to realize that after months of accumulating data, some queries become slower and slower.”
        But I find that this approach applies to almost everything related to Hibernate.
        Which is why I have got your book. 🙂

        Specifically though on the EntityGraph annotation, I have been checking the generated SQLs (quite fond of your query-logging articles/solutions) and I’m quite happy with them.
        For example, I can see LEFT OUTER JOIN when I add an attributePaths attribute to a relation to another table, which is exactly what I would have done with manual SQL.
        Obviously there can be cases where the generated SQL in not ideal, but in these cases (as an exception) I can resort to another method, like the one you show here.
        I don’t see this discussion as an “either-or” kind of discussion.

      6. Thanks, for buying my book. If you checked the SQL statements and they are efficient, then I think it’s just a matter of preference. I like to quickly tell if a query is optimal or not, which is why I don’t use Criteria API for non-dynamic queries. I tend to forget what a Criteria API is supposed to do after just 2 or 3 days :D. As for Entity Graphs, I agree that it fits perfectly into Spring Data JPA. I think that’s probably the best usage for it. However, as you probably realized it by now, Hibernate support for Entity Graph is not as good as it should be, so I;m more inclined to pick features that got more attention from the Core Developers.

Leave a Reply

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