Fetch List Using DTO projections using a Constructor Expression and JPQL
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
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