[英]Join and fetch just some properties not all the collection with JPA and Hibernate
[英]Collection fetch join
假設我有一個JPA實體和一個查詢:
@Entity
public class MyEntity {
@OneToMany(fetch = FetchType.LAZY)
private List<ChildEntity> children = new ArrayList<ChildEntity>();
}
public List<MyEntity> fetchAll() {
return em.createQuery("select distinct e from MyEntity e join fetch e.children")
.getResultList();
}
如果沒有不同的關鍵字,它將產生MyEntity和e.children的叉積。
是否同時使用distinct和join fetch以避免集合的N + 1 Select問題是否被視為一種好習慣? 它有副作用嗎?
您必須使用“ SELECT DISTINCT”,因為正在執行MyEntity和子級之間的笛卡爾積。
對不起我的英語不好
內在的連接不應該花招嗎?
public List<MyEntity> fetchAll() {
return em.createQuery("select e from MyEntity e inner join fetch e.children")
.getResultList();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.