findAll() 上的 @NamedEntityGraphs

5 spring-data-jpa spring-boot 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 {
Run Code Online (Sandbox Code Playgroud)

当我通过在存储库上使用它时

@EntityGraph(value = "graph.Employee.assignments", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findAll();
Run Code Online (Sandbox Code Playgroud)

我得到了预期的所有结果。但我需要几个版本的 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();
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试在存储库中定义新的方法名称,则会收到应用程序上下文错误,因为 Spring 无法解析方法名称。

有可能获得这样的方法吗?

谢谢

马蒂亚斯

cac*_*co3 5

添加@Query到您的方法中,该方法将选择所有Employees:

@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();
Run Code Online (Sandbox Code Playgroud)

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