将孩子跳过以获取父母-JPA [英] Skip child to fetching of parent - JPA
问题描述
我面临着递归获取数据的问题.我想避免孩子获取父数据.这导致了递归问题. 我已经在下面提到了
I am facing an issue where the data is getting fechted recursively. I wanted to avoid the child to fetch the parent data. Which is causing a recursive issue. I have mentioned the code below
Pojo结构
class Parent {
..
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List<Child> childs;
..
}
class Child {
..
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parentId")
private Parent parent;
..
}
以这种方式获取数据
` em = EMF.get().createEntityManager();
Query q = em.createQuery("Select p from Parent p", Parent.class);
List<Parent> parents = q.getResultList();
// Till this point all looks good but when the code gets executed
parent.getChilds();
`
它正在像这样获取数据:
It is fetching the data like this:
Parent
child1
Parent
child2
Parent
child2
Parent
..
..
child2
..
我不需要,我只想要这样的数据:
Which I dont need I just want the data like this:
Parent1
child1
child2
Parent2
child1
child2
child3
推荐答案
FetchType.EAGER
是合约,而FetchType.LAZY
只是提示,因为懒惰获取并非总是可能的.这可能取决于例如在您使用的JPA提供程序及其配置上.延迟获取对于一对一关系尤其有问题.
While FetchType.EAGER
is a contract, FetchType.LAZY
is only a hint, because lazy fetching is not always possible. This may depend e.g. on the JPA provider you use as well as on its configuration. Lazy fetching is particularly problematic with to-one relationships.
如果每个Child
都有一个Parent
,请尝试将optional=false
添加到您的@ManyToOne
中. 可能可以启用延迟抓取功能.
If every Child
has a Parent
, try adding optional=false
to your @ManyToOne
. This might enable lazy fetching.
由于Parent
实体已经加载到持久性上下文中,所以填充Children.parent
不应触发针对数据库的查询.您实际上看到了正在执行的查询吗?您如何知道正在加载Children.parent
?如果您正在访问该值以检查该事实,则很可能是您实际上触发了按需加载.
Since the Parent
entity is already loaded into the persistence context, populating Children.parent
shouldn't trigger queries against the database. Are you actually seeing queries being executed? How do you know Children.parent
is being loaded? If you are accessing the value to check that fact, chances are you are actually triggering the on-demand loading yourself.
这篇关于将孩子跳过以获取父母-JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!