Fetch List Using DTO projections using a Constructor Expression and JPQL

时光毁灭记忆、已成空白 提交于 2019-12-03 12:11:48

If you need to fetch parent entity with a collection of its nested child entities you can use this simple approach using @EntityGraph annotation or JPQL with join fetch:

@Entity
public class Parent {
    //...
    @OneToMany
    private List<Child> children;
}

@Entity
public class Child {
    //...
}

interface ParentRepo extends JpaRepository<Parent, Integer> {

    // with @EntityGraph
    @EntityGraph(attributePaths = "children")
    @Override
    List<Parent> findAll(); 

    // or manually
    @Query("select distinct p from Parent p left join fetch p.children")
    List<Parent> findWithQuery(); 
}

Note to use distinct in your query to avoid duplicate records.

Example: duplicate-parent-entities

More info: DATAJPA-1299

AFAIK, you can't use constructor expression which take a Collection.

See the JPA 2.2 Spec, section 4.14 BNF, read about the constructor expression:

constructor_expression ::=
    NEW constructor_name ( constructor_item {, constructor_item}* )
constructor_item ::=
    single_valued_path_expression |
    scalar_expression |
    aggregate_expression |
    identification_variable
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!