[英]Hibernate Many To One eager fetch N+1
I have the following JPA Entity: 我有以下JPA实体:
@Entity
@Table(name = "app")
public class App {
@Id
private String id;
@OneToOne(mappedBy = "app")
@PrimaryKeyJoinColumn
private FileDetails fileDetails;
@ManyToOne
private Developer developer;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
@OneToMany(mappedBy = "app", fetch = FetchType.EAGER)
private List<Image> images;
//getters, setters
}
As you can see the Image entity is set to EAGER
fetching. 如您所见,Image实体设置为
EAGER
fetching。 I want to select all entities using pagination and my Generic DAO uses this method: 我想使用分页选择所有实体,而我的通用DAO使用此方法:
public List<T> findByPage(int pageNum, int pageSize) {
CriteriaQuery<T> cq = getEntityManager()
.getCriteriaBuilder().createQuery(entity);
cq.select(cq.from(entity));
int firstResult = pageNum * pageSize;
return getEntityManager().createQuery(cq)
.setFirstResult(firstResult)
.setMaxResults(pageSize)
.getResultList();
}
However when I run the query I have a N+1 in relation to the Image entity. 但是,当我运行查询时,与Image实体相关的值为N + 1。 So for each App selected I get N selects for the number of Images.
因此,对于每个选择的应用程序,我都会获得N个用于选择图像的数量。 Isnt EAGER fetching supposed to solve this problem?
EAGER提取是否可以解决此问题? And what could be a solution?
还有什么解决方案?
IIRC, a join
( fetch
) to Image
in that query would solve such problem. IIRC,一个
join
( fetch
)以Image
在该查询会解决这个问题。
Now, as you need to specify the Image
class, I'll show you a non-generic solution, so you can verify if it works. 现在,由于需要指定
Image
类,因此我将向您展示一个非通用解决方案,以便您可以验证它是否有效。
// notice I changed all <T> to <App>
public List<App> findByPage(int pageNum, int pageSize) {
CriteriaQuery<App> cq = getEntityManager()
.getCriteriaBuilder().createQuery(entity);
Root<App> root = query.from(App.class); // added this
root.fetch("app"); // added this, this is the join
cq.select(cq.from(entity));
int firstResult = pageNum * pageSize;
return getEntityManager().createQuery(cq)
.setFirstResult(firstResult)
.setMaxResults(pageSize)
.getResultList();
}
I'm not 100% on this (I have't tested, and don't know if the "app"
string is the right way -- it should be the field which you want to "pull", but as this is many to one, I'm unsure, and placed the field in Image
that refers to App
instead), but I think the solution is somewhere around a join
and hopefully this points in the right direction. 我不是100%的人(我还没有测试过,也不知道
"app"
字符串是否是正确的方式-它应该是您要“拉取”的字段,但是因为有很多一,我不能确定,并放置在现场Image
是指App
,而不是),但我认为解决的办法是周围某处join
,并在正确的方向希望这点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.