【问题标题】:@NamedEntityGraphs on findAll()findAll() 上的 @NamedEntityGraphs
【发布时间】:2019-01-29 14:55:56
【问题描述】:

我在我的应用程序中使用@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();

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

有没有可能得到这样的方法?

谢谢

马蒂亚斯

【问题讨论】:

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


    【解决方案1】:

    @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();
    

    或者使用方法名 findAllWithAssignmentsBy findAllWithAbsencesBy 也应该可以工作

    【讨论】:

    • 嗨 caco3 谢谢你的回答。 @Query 的解决方案运行良好。这次真是万分感谢。我还尝试将 findAllWithAssignmentsBy() 作为存储库方法,但这不起作用,因为存储库需要一个参数(因为“by”)。
    • @MatthiasLauber 不客气。您尝试同时使用以By 结尾的方法名称,对吗?
    • 我不确定了,但我想,我尝试了一种方法。但我发现,如果使用参数,则不需要 Query。例如,我需要一个类似的数据库访问权限,在其中搜索与给定项目负责人相关的项目。在这里,我能够使用 EntityGraph 注释和 findAllWithProjectLeaderId(Long id) 而无需 Query
    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2016-07-07
    • 2012-05-18
    • 2016-09-07
    相关资源
    最近更新 更多