The best way to handle the LazyInitializationException

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 you 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 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.

Enter your email address to follow this blog and receive notifications of new posts by email.

Advertisements

42 thoughts on “The best way to handle 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.

    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. 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.

  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. 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.

  4. Although I agree with some of the observations/advice you present here, there are a few clarifications/corrections that need to be made:

    I don’t understand why you insist on emphasizing the old saw about the value of returning a sub-projection of a domain object (a subset of it’s table’s columns); that’s not how databases work; a database row is just a leaf node in the clustered index; and given how file-systems/OS cache’s work, the cost of “loading” 15 columns vs 2 is the same, even if the row needs to be fetched from disk (since filesystems operate on data pages, not random bytes); and of course if the row is already in memory, then there is also no performance difference (even the originators of Hibernate understand this).
    Now there can be some exceptions to this rule (viz. covering queries/indices or large binary (BLOB) columns), but those are exceptions and not the rule. If there is any measurable difference in latency, it’s likely due to misconfiguration of the database and/or driver. and is probably 100th on the list of performance issues you should focus on.
    On the one hand, you write “you should always fetch just as much data you need to fulfill the requirements of a given business logic use case” – and on this I 100% agree and is probably #1 on the performance list. On the other, you emphasize the value of LAZY loading; but those two statements are in direct contradiction!
    Even if we ignore n + 1 selects (which turns a bad situation into a catastrophe), the latency hit to go to the database twice (using 2 SELECTS) vs. going to the database once (using a JOIN) is significant, that’s just an empirical observation.

    Any RDBMS worth its name is efficient at processing JOINS (they’re designed from the ground up to be so), so if you need to load an entity association in order to process a request/unit of work, then it is better to retrieve the data in as few roundtrips to the database as possible.

    And of course this doesn’t even address the significant cost of leaving the connection/transaction open to maintain the semantics of “lazily” traversing domain associations (which you correctly identify elsewhere and makes OSIV a non-starter).

    Now of course this doesn’t imply that you should promiscuously load unneeded associations; go back to your original admonition:
    “you should always fetch just as much data you need to fulfill the requirements of a given business logic use case”
    I would only add the clarification ” and in as few round trips as practicable”

    The bottom line is that if “lazy loading” is ever actually triggered at runtime, then that’s a major performance hit; if you want a high-performant, efficient system, then you shouldn’t rely on it

    1. that’s not how databases work; a database row is just a leaf node in the clustered index;

      What if you use Oracle and PostgreSQL, and You use Heap table indexes? Your statement is only true for SQL Server and MySQL.

      On the other, you emphasize the value of LAZY loading; but those two statements are in direct contradiction!

      No, they are not in any contradiction. You can use JOINs or secondary selects with LAZY loading as well. There’s no limitation for LAZY.

      Even if we ignore n + 1 selects

      That’s a very dangerous statement, and I even advise people to assert the automated generated SQL statements to catch N+1 issues right from the test phase.

      The bottom line is that if “lazy loading” is ever actually triggered at runtime, then that’s a major performance hit; if you want a high-performant, efficient system, then you shouldn’t rely on it

      In fact, I even advise people to use DTOs instead of entities, for read-only projections. As for entities, of course, you should only fetch what you need, and that should happen explicitly with a JOIN FETCH or a Hibernate#initialize method call. Auto-loading triggers like OSIV or temporary session are Anti-Patterns.

      1. Heap tables still store their full rows contiguously on disk (it would be insane not to do so); there might be rare exceptions, e.g. when rows spillover from one data page to the next, but the general principle still holds, bytes are loaded from the file system in pages at a time, that is the point (and as I mentioned, even the Hibernate authors are aware of this and point out the futility of loading sub-projections of an entity).

        I think we’re using “lazy loading” differently; you’re using it in a narrow sense in terms of configuring entity relationships (via JPA annotations or .hbm files); I use it in terms of the general pattern of “deferring loading of relationships until needed/requested”, which by definition eschews JOINs (i.e. eager-loading) in favor of an additional roundtrip to the database (via another separate SELECT). It is meaningless to conflate JOIN FETCHES with “LAZY LOADING” – JOINS are eager-loading (in the abstract sense) by definition, regardless of any annotation

        My point is that it is meaningless to talk of eager fetching (i.e. JOINS) as bad and lazy loading (deferred additional SELECTs as good); it all depends on the use case; if I need a PostComment’s#post loaded to satisfy a particular use case, then eagerly loading the Post (via a JOIN) is optimal; if I don’t need Post loaded, then “lazy loading” is optimal (because I save a superfluous JOIN). end.of.story. Statements such as “lazy loading is important for performance” are just wrong; in fact, the only situation in which “lazy loading” is performant, is when it’s never triggered; you simply cannot pretend that the additional roundtrip to the database is free – far from it.

        And as you are aware, even in the case of lazy-loading not being triggered, there is a significant penalty being paid, viz. the cost of keeping open the session/connection/transaction in order to maintain lazy-load semantics; in that sense lazy-loading is always sub-optimal, while at least eager-loading is only sometimes sub-optimal.

        What those of us who understand RDBMS and ORMs should emphasize, is that if you want low-latency, high-throughput applications, you must know what data needs to be loaded as part of fulfilling a use case/request, and load that data as efficiently as possible, which 99% of the time means going to the database as rarely as possible; there’s just no way around it and shame on the Java community/ORM authors for obscuring that inescapable reality

      2. We are o the same wavelength but we just got lost in naming concepts. Indeed, when I said lazy loading, I was referring to preferring FetchType.LAZY and controlling the fetching profile on a per business use case basis. You are right that it makes no sense to defer the loading so that the fetching is triggered by the UI or something like that.

        However, as useful as JOINs are for fetching @ManyToOne or @OneToOne associations, you still don’t want to JOIN FETCH multiple @OneToMany collections because, otherwise, you’d end up with a Cartesian Product. Imagine fetching a list of Post entities, along with Comments and Tags. Both the Comment and the Tag are related to a Post, but the Tag and the Comment are still unrelated to each other. In this case, it makes sense to JOIN FETCH just one collection, and trigger the loading of the second one with a secondary SELECT, by calling Hibernate#initialize utility.

  5. Vlad I read your book. I want to check if I understood well what I have read:
    – use DTOs only when you need to read data
    – use entities only when you need to modify data

    Personally I think if you use these pattern you get rid of lazy exceptions, entity states and pretty much all the things that cause pain in Hibernate. Plus you do easy pagination by using DTOs.

    Is my understanding correct?

    Also, do you have an email that people can reach if they have some tough hibernate questions?

    Kind regards,
    Aurelian

    1. Thanks, Aurelian for buying my book

      Your understanding is correct. DTOs are ideal for read-only projections when you don’t need to preserve the state of the data being read so that you can overcome anomalies like lost updates.

      Related to questions about Hibernate, just ask them on StackOverflow and ping me on Twitter (@vlad_mihalcea). This way, other people can benefit from a given answer that I give you.

  6. I run into this problem all the time developing web services with JAXB, which tries to get the entire graph. Why can’t you have a setting that just returns a null if the collection hasn’t been loaded instead of throwing the Lazy Load Exception?

    1. You could use lazy_load_notrans setting, but it has a cost. Anyway, this setting is better than returning null. The best way to handle this issue is to fetch just the associations that you need.

      1. I agree that it’s best to get all the data you need in the data layer but the problem is that the entities and collections I don’t need will still trigger a lazy load exception when JAXB tries to serialize everything. That’s why it would be nice to have a read only/POJO option available for every query.

  7. Hello Vlad,

    Nice article, however it is not explained why hibernate does throw LazyInitException.
    Could you please explain why hibernate is designed in such way ? Why it couldnt just execute another query to select the needed Lazy Collection/Reference

      1. Bought your book, however could not find something concrete why, just why it does throw LazyInitExceptions.

        If I do select a Entity with lazy reference and after that the session is closed, why it just can’t re-open a session a hit a select to database?

  8. Thank you for the article, I have a question regarding the DTO projection, what if the DTO contains et’s say 2 lists, I cannot pass 2 lists to the constructor of PostCommentDTO.

    What I’m doing is iterate through the query result (without the projection) and create the DTO list myself. Is there a better alternative?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s