I have created a simple Spring boot project with Spring data.
I have a TagGroup Entity which has one to many relation with Tags.
@Entity
@Table(name = "TAG_GROUP")
public class TagGroup{
@OneToMany(fetch=FetchType.LAZY,mappedBy = "tagGroup")
private Set<Tag> tagList;
}
The Tag Entity is as below
@Entity
@Table(name = "TAGS")
public class Tag {
@ManyToOne(optional = false,fetch=FetchType.LAZY)
@JoinColumn(name = "TAG_GROUP_ID")
private TagGroup tagGroup;
}
I am using Spring data extending the JPArepository and using its findAll method.
The problem , the Lazy fetch doesn't work BUT Infact it is loading the tag list also without calling the tagList explicitly as If it is EAGER...
Can anybody please tell me what I am doing wrong here ?
This is because of property spring.jpa.open-in-view=true.
As per the spring-boot-configuration Spring boot applications use spring.jpa.open-in-view=true.
With this property it
Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request.
So in your case, subsequently when you call the getTagList() i.e., retrieve the tagList, it subsequently fires another query to fetch the tagList as the the EntityManager is still open.
As you might know, LazyInitializationException is never thrown if the entityManager that has loaded the parent is still open.
To override this, you can add spring.jpa.open-in-view=false in your application.properties/application.yml and then you should see LazyInitializationException.
来源:https://stackoverflow.com/questions/36282018/fetch-type-lazy-still-causes-eager-loading-hibernate-spring-data