Reputation: 3503
Working on a project which uses Spring/JPA/Rest. We have a class which has a @OneToMany field(say Student in the example below) which is marked for LAZY loading. However, when we test the output in postman, we see the complete json for the Course and all the student details.
public class CourseList{
private String Course;
//other fields
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private <Set>Student students;
//Getters and Setters
}
My understanding of Lazy Loading is that the fetch for the database happens only on explicit call to the particular field. We should expect to see only the Course details coming up in the json and not the address details..why are we seeing address details too?
Can someone help clarify, if my understanding of LazyLoading is incorrect or whether it doesn't apply in this case for some reason? Thanks.
Upvotes: 2
Views: 1400
Reputation: 5875
Your JSON library will read all the properties of the object recursively in order to generate the output. So it is accessing the students set.
You have three possible outcomes here, from my experience:
The JSON serialization happens outside the JPA session so the object is detached. Since the students set is lazy loaded you will get an exception.
The JSON serialization happens inside the JPA session so when the JSON library accesses the students set then the data is fetched from the database.
The JSON serialization happens outside the JPA session but you have, somehow, accessed the students set before that and inside the JPA session. The data was fetched and is available on the detached object.
I've had this issue and I've forced the third option. My first try gave me the exception (option 1) but then I forced a read from the lazy loaded set just to fetch the data for the JSON serialization.
Upvotes: 3
Reputation: 3466
Spring Boot registers an OpenEntityManagerInViewInterceptor. Spring boot default configuration spring.jpa.open-in-view = true
.
If you want to disable that behaviour, add the configuration spring.jpa.open-in-view = false
.
Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request.
Upvotes: 1
Reputation: 83
// ^_^?
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public Link Student student;
You want to return CourseList
including List<Student>
, You need to create the Response
or Student
entity you must be sure that no @ManyToOne
to CourseList
, otherwise happens StackOverflow Error.
This tutorial also refers to that problem: Spring Data : JPA (Hibernate) One To Many Relationships and N+1 Query Problem
Upvotes: 0