Arockiasamy
Arockiasamy

Reputation: 60

Make Lazy initialization objects as null, while object is with hibernate proxy in jpa

For example I have three classes as follows

User{
   Integer id;
   ...
}

Book{
  Integer id;
  ....

  @ManyToOne(fetch=FetchType.lazy)
  User insertedBy;
}

Author{
   Integer id;
   List<Book> books;
}

Now I need to show the author list with their written books in same page so I fetch authors with findAll() method using jpa repository. here I don't need the inserted by column of books so I mad them with lazy load.

When I tried to converts these author lists into json object with Gson. it gives lazy load exception in User class (Hibernate proxy... no session found.....)

I have followed many of the ways given in this network like TypeAdapters. nothing helps me. I just wanted to make insertedBy column of Books as null in lazy load.

for now I am using Dto classes to avoid insertedBy / make insertedBy as null.

Is there any other simple way without converting it into Dto.

I faced this issue many times. all those time I was end up with converting into Dto.

If anyone knows the answer please help me solve.

Upvotes: 0

Views: 882

Answers (1)

YGR
YGR

Reputation: 98

"lazy-load" in Hibernate means children does not actually get loaded when loading the parent, typically when you try to access a child during iteration it gets loaded. In your case you receive this lazy load exception because by the time when gson try to access the child to map it to a JSON object the session has closed already.

May be you can ask GSON to ignore that field while mapping to JSON by using ExclusionStrategy class provided by Gson.

Upvotes: 1

Related Questions