简体   繁体   English

集合获取连接

[英]Collection fetch join

Suppose I have an JPA entity and a query: 假设我有一个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();
}

Without distinct keyword it will do a cross-product of MyEntity and e.children. 如果没有不同的关键字,它将产生MyEntity和e.children的叉积。

Is it considered a good practice to use both distinct and join fetch to avoid N+1 Select problem with collections? 是否同时使用distinct和join fetch以避免集合的N + 1 Select问题是否被视为一种好习惯? Does it have side-effects? 它有副作用吗?

You must use "SELECT DISTINCT" because is being executed a cartesian product between MyEntity and children. 您必须使用“ SELECT DISTINCT”,因为正在执行MyEntity和子级之间的笛卡尔积。

Sorry for my English 对不起我的英语不好

shouldnt an inner join do the trick? 内在的连接不应该花招吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM