How to Solve Lazy initialize Exception to get the list of data using hibernate Bidirectional One to Many Mapping



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Consider the following two tables - posts and comments of a Blog database schema where the posts table has a one-to-many relationship with the comments table



I'm using Bidirectional One to Many Mapping, because my child entities are limited only.



In Bidirectional One to Many Mapping, I wrote one rest call to get all the post with appropriate comments for the post Using default find all method in JPA Repository.



But the following exception occurred:



"message": "Could not write JSON: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.insights.apartmento.modal.Post["comments"])",


My Pojo class as follows




In POST POJO



@Entity
@Table(name = "posts")
public class Post
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Size(max = 100)
@Column(unique = true)
private String title;

@Size(max = 250)
private String description;

@Lob
private String content;

@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "post")
private Set<Comment> comments = new HashSet<>();

// Getters and Setters (Omitted for brevity)




In Comments POJO




@Entity
@Table(name = "comments")
public class Comment
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Lob
private String text;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id", nullable = false)
private Post post;

// Getters and Setters (Omitted for brevity)










share|improve this question






























    0















    Consider the following two tables - posts and comments of a Blog database schema where the posts table has a one-to-many relationship with the comments table



    I'm using Bidirectional One to Many Mapping, because my child entities are limited only.



    In Bidirectional One to Many Mapping, I wrote one rest call to get all the post with appropriate comments for the post Using default find all method in JPA Repository.



    But the following exception occurred:



    "message": "Could not write JSON: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.insights.apartmento.modal.Post["comments"])",


    My Pojo class as follows




    In POST POJO



    @Entity
    @Table(name = "posts")
    public class Post
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 100)
    @Column(unique = true)
    private String title;

    @Size(max = 250)
    private String description;

    @Lob
    private String content;

    @OneToMany(cascade = CascadeType.ALL,
    fetch = FetchType.LAZY,
    mappedBy = "post")
    private Set<Comment> comments = new HashSet<>();

    // Getters and Setters (Omitted for brevity)




    In Comments POJO




    @Entity
    @Table(name = "comments")
    public class Comment
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Lob
    private String text;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id", nullable = false)
    private Post post;

    // Getters and Setters (Omitted for brevity)










    share|improve this question


























      0












      0








      0








      Consider the following two tables - posts and comments of a Blog database schema where the posts table has a one-to-many relationship with the comments table



      I'm using Bidirectional One to Many Mapping, because my child entities are limited only.



      In Bidirectional One to Many Mapping, I wrote one rest call to get all the post with appropriate comments for the post Using default find all method in JPA Repository.



      But the following exception occurred:



      "message": "Could not write JSON: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.insights.apartmento.modal.Post["comments"])",


      My Pojo class as follows




      In POST POJO



      @Entity
      @Table(name = "posts")
      public class Post
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;

      @Size(max = 100)
      @Column(unique = true)
      private String title;

      @Size(max = 250)
      private String description;

      @Lob
      private String content;

      @OneToMany(cascade = CascadeType.ALL,
      fetch = FetchType.LAZY,
      mappedBy = "post")
      private Set<Comment> comments = new HashSet<>();

      // Getters and Setters (Omitted for brevity)




      In Comments POJO




      @Entity
      @Table(name = "comments")
      public class Comment
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;

      @NotNull
      @Lob
      private String text;

      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "post_id", nullable = false)
      private Post post;

      // Getters and Setters (Omitted for brevity)










      share|improve this question
















      Consider the following two tables - posts and comments of a Blog database schema where the posts table has a one-to-many relationship with the comments table



      I'm using Bidirectional One to Many Mapping, because my child entities are limited only.



      In Bidirectional One to Many Mapping, I wrote one rest call to get all the post with appropriate comments for the post Using default find all method in JPA Repository.



      But the following exception occurred:



      "message": "Could not write JSON: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.insights.apartmento.modal.Post.comments, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.insights.apartmento.modal.Post["comments"])",


      My Pojo class as follows




      In POST POJO



      @Entity
      @Table(name = "posts")
      public class Post
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;

      @Size(max = 100)
      @Column(unique = true)
      private String title;

      @Size(max = 250)
      private String description;

      @Lob
      private String content;

      @OneToMany(cascade = CascadeType.ALL,
      fetch = FetchType.LAZY,
      mappedBy = "post")
      private Set<Comment> comments = new HashSet<>();

      // Getters and Setters (Omitted for brevity)




      In Comments POJO




      @Entity
      @Table(name = "comments")
      public class Comment
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;

      @NotNull
      @Lob
      private String text;

      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "post_id", nullable = false)
      private Post post;

      // Getters and Setters (Omitted for brevity)







      spring hibernate one-to-many lazy-initialization






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 16:28







      Seenivasan Sankaran

















      asked Nov 15 '18 at 15:54









      Seenivasan SankaranSeenivasan Sankaran

      12




      12






















          3 Answers
          3






          active

          oldest

          votes


















          0














          You are trying to serialize directly the Post Object. What happens is that Jackson marshaller tries to build a JSON from the full class, included the private Set<Comment> comments



          Since you are using a Lazy FetchType (correctly according to me) Hibernate will throw a LazyInitializationException
          You can avoid this in several way:



          1. You can ignore the comments Set in the generated JSON by using the @JsonIgnore annotation on this property

          2. You can fully load the Post object but using a different FetchType (e.g EAGER or JOIN)

          3. You can use the Hibernate.initialize method

          Which solution to use? Well this depends on your use case. In any case I strongly suggest you to avoid the solution number 2 (fully load the Post object but using a different FetchType (e.g. EAGER or JOIN) because this means you'll always load Posts with all comments and this is very impactful on performance






          share|improve this answer
































            0














            Your @OneToMany association gets fetched lazily, which should always be your preferred FetchType. It performs much better than EAGER fetching.



            But then you need to make sure that you initialize all required associations before you close the Session or send the entity object to any client. In your case, the JSON marshaling happens after your Session got closed, which caused the exception.



            There are multiple ways to initialize a lazily fetched association. The easiest one is a JOIN FETCH clause in a JPQL query, e.g.:



            SELECT p FROM Post p LEFT JOIN FETCH p.comments c WHERE p.id = :id


            If you're using em.find to load the Post entity, you either need to replace it with a JPQL query or use an EntityGraph.






            share|improve this answer






























              -2














              In one to many mapping, define fetch type as EAGER.



              @OneToMany(cascade = CascadeType.ALL,
              fetch = FetchType.EAGER,
              mappedBy = "post")





              share|improve this answer























              • Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                – Thorben Janssen
                Nov 16 '18 at 9:55












              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323204%2fhow-to-solve-lazy-initialize-exception-to-get-the-list-of-data-using-hibernate-b%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              You are trying to serialize directly the Post Object. What happens is that Jackson marshaller tries to build a JSON from the full class, included the private Set<Comment> comments



              Since you are using a Lazy FetchType (correctly according to me) Hibernate will throw a LazyInitializationException
              You can avoid this in several way:



              1. You can ignore the comments Set in the generated JSON by using the @JsonIgnore annotation on this property

              2. You can fully load the Post object but using a different FetchType (e.g EAGER or JOIN)

              3. You can use the Hibernate.initialize method

              Which solution to use? Well this depends on your use case. In any case I strongly suggest you to avoid the solution number 2 (fully load the Post object but using a different FetchType (e.g. EAGER or JOIN) because this means you'll always load Posts with all comments and this is very impactful on performance






              share|improve this answer





























                0














                You are trying to serialize directly the Post Object. What happens is that Jackson marshaller tries to build a JSON from the full class, included the private Set<Comment> comments



                Since you are using a Lazy FetchType (correctly according to me) Hibernate will throw a LazyInitializationException
                You can avoid this in several way:



                1. You can ignore the comments Set in the generated JSON by using the @JsonIgnore annotation on this property

                2. You can fully load the Post object but using a different FetchType (e.g EAGER or JOIN)

                3. You can use the Hibernate.initialize method

                Which solution to use? Well this depends on your use case. In any case I strongly suggest you to avoid the solution number 2 (fully load the Post object but using a different FetchType (e.g. EAGER or JOIN) because this means you'll always load Posts with all comments and this is very impactful on performance






                share|improve this answer



























                  0












                  0








                  0







                  You are trying to serialize directly the Post Object. What happens is that Jackson marshaller tries to build a JSON from the full class, included the private Set<Comment> comments



                  Since you are using a Lazy FetchType (correctly according to me) Hibernate will throw a LazyInitializationException
                  You can avoid this in several way:



                  1. You can ignore the comments Set in the generated JSON by using the @JsonIgnore annotation on this property

                  2. You can fully load the Post object but using a different FetchType (e.g EAGER or JOIN)

                  3. You can use the Hibernate.initialize method

                  Which solution to use? Well this depends on your use case. In any case I strongly suggest you to avoid the solution number 2 (fully load the Post object but using a different FetchType (e.g. EAGER or JOIN) because this means you'll always load Posts with all comments and this is very impactful on performance






                  share|improve this answer















                  You are trying to serialize directly the Post Object. What happens is that Jackson marshaller tries to build a JSON from the full class, included the private Set<Comment> comments



                  Since you are using a Lazy FetchType (correctly according to me) Hibernate will throw a LazyInitializationException
                  You can avoid this in several way:



                  1. You can ignore the comments Set in the generated JSON by using the @JsonIgnore annotation on this property

                  2. You can fully load the Post object but using a different FetchType (e.g EAGER or JOIN)

                  3. You can use the Hibernate.initialize method

                  Which solution to use? Well this depends on your use case. In any case I strongly suggest you to avoid the solution number 2 (fully load the Post object but using a different FetchType (e.g. EAGER or JOIN) because this means you'll always load Posts with all comments and this is very impactful on performance







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 16 '18 at 6:05









                  Rezwan

                  336213




                  336213










                  answered Nov 15 '18 at 16:25









                  Angelo ImmediataAngelo Immediata

                  4,61941638




                  4,61941638























                      0














                      Your @OneToMany association gets fetched lazily, which should always be your preferred FetchType. It performs much better than EAGER fetching.



                      But then you need to make sure that you initialize all required associations before you close the Session or send the entity object to any client. In your case, the JSON marshaling happens after your Session got closed, which caused the exception.



                      There are multiple ways to initialize a lazily fetched association. The easiest one is a JOIN FETCH clause in a JPQL query, e.g.:



                      SELECT p FROM Post p LEFT JOIN FETCH p.comments c WHERE p.id = :id


                      If you're using em.find to load the Post entity, you either need to replace it with a JPQL query or use an EntityGraph.






                      share|improve this answer



























                        0














                        Your @OneToMany association gets fetched lazily, which should always be your preferred FetchType. It performs much better than EAGER fetching.



                        But then you need to make sure that you initialize all required associations before you close the Session or send the entity object to any client. In your case, the JSON marshaling happens after your Session got closed, which caused the exception.



                        There are multiple ways to initialize a lazily fetched association. The easiest one is a JOIN FETCH clause in a JPQL query, e.g.:



                        SELECT p FROM Post p LEFT JOIN FETCH p.comments c WHERE p.id = :id


                        If you're using em.find to load the Post entity, you either need to replace it with a JPQL query or use an EntityGraph.






                        share|improve this answer

























                          0












                          0








                          0







                          Your @OneToMany association gets fetched lazily, which should always be your preferred FetchType. It performs much better than EAGER fetching.



                          But then you need to make sure that you initialize all required associations before you close the Session or send the entity object to any client. In your case, the JSON marshaling happens after your Session got closed, which caused the exception.



                          There are multiple ways to initialize a lazily fetched association. The easiest one is a JOIN FETCH clause in a JPQL query, e.g.:



                          SELECT p FROM Post p LEFT JOIN FETCH p.comments c WHERE p.id = :id


                          If you're using em.find to load the Post entity, you either need to replace it with a JPQL query or use an EntityGraph.






                          share|improve this answer













                          Your @OneToMany association gets fetched lazily, which should always be your preferred FetchType. It performs much better than EAGER fetching.



                          But then you need to make sure that you initialize all required associations before you close the Session or send the entity object to any client. In your case, the JSON marshaling happens after your Session got closed, which caused the exception.



                          There are multiple ways to initialize a lazily fetched association. The easiest one is a JOIN FETCH clause in a JPQL query, e.g.:



                          SELECT p FROM Post p LEFT JOIN FETCH p.comments c WHERE p.id = :id


                          If you're using em.find to load the Post entity, you either need to replace it with a JPQL query or use an EntityGraph.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 16 '18 at 9:52









                          Thorben JanssenThorben Janssen

                          40517




                          40517





















                              -2














                              In one to many mapping, define fetch type as EAGER.



                              @OneToMany(cascade = CascadeType.ALL,
                              fetch = FetchType.EAGER,
                              mappedBy = "post")





                              share|improve this answer























                              • Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                                – Thorben Janssen
                                Nov 16 '18 at 9:55
















                              -2














                              In one to many mapping, define fetch type as EAGER.



                              @OneToMany(cascade = CascadeType.ALL,
                              fetch = FetchType.EAGER,
                              mappedBy = "post")





                              share|improve this answer























                              • Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                                – Thorben Janssen
                                Nov 16 '18 at 9:55














                              -2












                              -2








                              -2







                              In one to many mapping, define fetch type as EAGER.



                              @OneToMany(cascade = CascadeType.ALL,
                              fetch = FetchType.EAGER,
                              mappedBy = "post")





                              share|improve this answer













                              In one to many mapping, define fetch type as EAGER.



                              @OneToMany(cascade = CascadeType.ALL,
                              fetch = FetchType.EAGER,
                              mappedBy = "post")






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 15 '18 at 16:24









                              RezwanRezwan

                              336213




                              336213












                              • Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                                – Thorben Janssen
                                Nov 16 '18 at 9:55


















                              • Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                                – Thorben Janssen
                                Nov 16 '18 at 9:55

















                              Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                              – Thorben Janssen
                              Nov 16 '18 at 9:55






                              Please don't use FetchType.EAGER. It forces Hibernate to always fetch the associated entities, even if you don't need them. That's one of the most common performance pitfalls with JPA and Hibernate.

                              – Thorben Janssen
                              Nov 16 '18 at 9:55


















                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323204%2fhow-to-solve-lazy-initialize-exception-to-get-the-list-of-data-using-hibernate-b%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Use pre created SQLite database for Android project in kotlin

                              Darth Vader #20

                              Ondo