延迟加载不起作用 - jpa
大家好, 我有三张桌子“儿童”、“宠物”和“玩具”。宠物有一个关于孩子 ID 的参考键,而玩具有一个关于狗 ID 的参考键。 我想加载有关孩子及其宠物的所有数据,但我不想加载
@OneToMany(mappedBy = "petEntity", fetch = FetchType.LAZY)
public Set<PetEntity> getPetEntitySet() {
return petEntitySet;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ChildId", insertable = false, updatable = false)
public ChildEntity getChildEntity() {
return childEntity;
}
一组玩具的相同玩具数据。
加载我拥有的数据,
List<ChildEntity> list = entityManager.createQuery(
"SELECT c FROM ChildEntity c "+
"LEFT JOIN FETCH c.petEntitySet ",
ChildEntity.class).getResultList();
return list;
但这东西会加载我所有的数据,而不仅仅是有关孩子和他的宠物的信息。
我怎样才能抑制实体管理器只加载表中的数据,而不是在我不想要的时候进行连接
谢谢你的建议,
我忘了提到在这个追逐中它不仅加载所有数据,而且它不仅仅返回子元素的一份副本
Hy all,
I have three tables Child, Pet and Toy. Pet has a reference key the child id, and a toy has a reference key to a dog id.
I want to load all data about a Child and his pets, but i don't want to load the toy data
@OneToMany(mappedBy = "petEntity", fetch = FetchType.LAZY)
public Set<PetEntity> getPetEntitySet() {
return petEntitySet;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ChildId", insertable = false, updatable = false)
public ChildEntity getChildEntity() {
return childEntity;
}
same for set of toys.
to load data i have
List<ChildEntity> list = entityManager.createQuery(
"SELECT c FROM ChildEntity c "+
"LEFT JOIN FETCH c.petEntitySet ",
ChildEntity.class).getResultList();
return list;
but this thing loads me all data, not just the information about child and his pets.
How can i suppress the entity manager to load only the data in the table, and not to make joins when i don't want that
Thanks for your advices
i forgot to mention that in this chase it doesn't only load all data, but it returns more than just one copy of a child elemnt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它加载更多数据的原因是因为您使用了关键字
fetch
。这将EAGERLY
加载孩子的宠物。只需删除
fetch
,就会发生延迟加载。更新
我发现这实际上是您想要的,因此只需确保在所有相关类中正确覆盖
equals()
和hashCode()
即可,因为我假设您正在使用Set
。通过这种方式,jpa 知道如何查找重复项
第二次更新
是的,您可以在查询中轻松使用
DISTINCT
。只需在您的选择中添加
DISTINCT
The reason why it is loading more data is because you are using the keyword
fetch
. This willEAGERLY
load whatever the child's pets.Just remove the
fetch
and lazy loading will occur.Update
I see that this is actually what you want, so just ensure
equals()
andhashCode()
is correctly overriden in all relevant classes, as I assume you are usingSet
.In this way, jpa knows how to look for duplicates
Second update
Yes you can easily use
DISTINCT
in your queries.Just add
DISTINCT
in your select