Fetch List Using DTO projections using a Constructor Expression and JPQL

前端 未结 3 1243
無奈伤痛
無奈伤痛 2021-02-13 18:14

Perform a search on DisabScreenRequest and fetch its child details also. Using DTO projections using a Constructor Expression and JPQL.

The parent entity with a child

3条回答
  •  萌比男神i
    2021-02-13 18:54

    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 children;
    }
    
    @Entity
    public class Child {
        //...
    }
    
    interface ParentRepo extends JpaRepository {
    
        // with @EntityGraph
        @EntityGraph(attributePaths = "children")
        @Override
        List findAll(); 
    
        // or manually
        @Query("select distinct p from Parent p left join fetch p.children")
        List findWithQuery(); 
    }
    

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

    Example: duplicate-parent-entities

    More info: DATAJPA-1299

提交回复
热议问题