findAll()上的@NamedEntityGraphs

时间:2019-01-29 14:55:56

标签: spring-boot spring-data-jpa entitygraph

我在应用程序中使用@NamedEntityGraph

@NamedEntityGraphs({
    @NamedEntityGraph(name = "graph.Employee.assignments", attributeNodes = @NamedAttributeNode("assignmentProjectEmployeeSet")),
    @NamedEntityGraph(name = "graph.Employee.absences", attributeNodes = @NamedAttributeNode("absences"))
})enter code here`public class Employee {

当我通过

在存储库中使用它时
@EntityGraph(value = "graph.Employee.assignments", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findAll();

我得到了所有预期的结果。但是对于不同的情况,我将需要多个版本的findAll()。

@EntityGraph(value = "graph.Employee.assignments", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findAllWithAssignments();

@EntityGraph(value = "graph.Employee.absences", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findAllWithAbsences();

但是,如果我尝试在存储库中定义一个新的方法名称,则会收到Application Context错误,因为Spring无法解析此方法名称。

是否有可能获得这种方法?

谢谢

Matthias

1 个答案:

答案 0 :(得分:2)

@Query添加到您的方法中,这些方法将选择所有Employee

@Query("select e from Employee e")
@EntityGraph(value = "graph.Employee.assignments", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findAllWithAssignments();

@Query("select e from Employee e")
@EntityGraph(value = "graph.Employee.absences", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findAllWithAbsences();

或使用方法名称findAllWithAssignmentsBy findAllWithAbsencesBy也应有效