简体   繁体   中英

Collection fetch join

Suppose I have an JPA entity and a query:

@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.

Is it considered a good practice to use both distinct and join fetch to avoid N+1 Select problem with collections? Does it have side-effects?

You must use "SELECT DISTINCT" because is being executed a cartesian product between MyEntity and children.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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