获取类型LAZY仍然会导致Eager加载Hibernate Spring数据 [英] Fetch Type LAZY still causes Eager loading Hibernate Spring data
问题描述
我有一个TagGroup Entity,它与Tags有一对多关系。
@Entity
@Table(name =TAG_GROUP)
公共类TagGroup {
@ OneToMany(fetch = FetchType.LAZY,mappedBy =tagGroup)
private Set< Tag>标记列表;
标签实体如下
@Entity
@Table(name =TAGS)
public class Tag {
@ ManyToOne(可选= false,fetch = FetchType.LAZY)
@JoinColumn(name =TAG_GROUP_ID)
私有TagGroup tagGroup;
}
我使用Spring数据扩展JPArepository并使用它的findAll方法。
这个问题,Lazy fetch不起作用,但事实上它加载标签列表时也没有显式调用tagList,因为如果它是EAGER ...
任何人都可以告诉我我在做什么错吗?
这是因为属性 spring.jpa.open-in-view = true
。
根据< a href =https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html =nofollow> spring-boot-configuration Spring启动应用程序使用 spring.jpa.open-in-view = true
。
使用此属性
注册OpenEntityManagerInViewInterceptor。将JPA EntityManager绑定到线程以处理请求的整个处理。
所以在你的情况下,随后当你调用 getTagList()
即检索 tagList
,它随后触发另一个查询来获取 tagList
> EntityManager
仍然打开。
entityManager
仍处于打开状态,则永远不会抛出LazyInitializationException 。 为了覆盖这个,你可以在 application.properties / application.yml中添加
spring.jpa.open-in-view = false
/ code>,然后你应该看到 LazyInitializationException
。
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
.
这篇关于获取类型LAZY仍然会导致Eager加载Hibernate Spring数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!