Spring-JPA-如何从自联接表中输出受限字段

时间:2019-04-05 09:51:05

标签: java hibernate spring-data-jpa

我有一个名为employee的实体,该实体具有自我连接的能力。加入将代表谁是该员工的经理。当查询记录时,我将获得员工的整个层次结构。

我希望实现的是仅获取经理的几个领域,而不希望获取员工经理的经理。

我尝试使用@NamedEntityGraph进行操作,但无法获得预期的输出。 也使用了Projections

我也尝试了此处提到的方法

  1. JPA Self Join using JoinTable

  2. Self join Spring JPA

注意-我不希望使用@Query注释

@Entity
public class Employee {
    @Id
    @Column(name = "employeeId", nullable = false)
    private String employeeId;

    @Column(name = "firstName", nullable = false)
    private String firstName;

    @Column(name = "lastName", nullable = false)
    private String lastName;

    @Column(name = "middleName")
    private String middleName;

    @Column(name = "dateOfJoining", nullable = false)
    private LocalDate dateOfJoining;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "line_manager_id")
    private Employee manager;

}

实际结果-

{
   "firstName":"Super",
   "lastName":"Manager",
   "middleName":"",
   "dateOfJoining":"2012-12-31",
   "manager":{
      "firstName":"Super",
      "lastName":"Manager",
      "middleName":"",
      "dateOfJoining":"2012-12-31",
      "manager":{
         "firstName":"Admin",
         "lastName":"User",
         "middleName":"",
         "dateOfJoining":"2012-12-31",
         "manager":{
            "firstName":"Admin",
            "lastName":"User",
            "middleName":"",
            "dateOfJoining":"2012-12-31",
            "manager": null,
            "employeeId":"P67"
         },
         "employeeId":"P68"
      },
      "employeeId":"P69"
   },
   "employeeId":"P70"
}

预期结果


{
   "firstName":"Super",
   "lastName":"Manager",
   "middleName":"",
   "dateOfJoining":"2012-12-31",
   "manager":{
      "firstName":"Super",
      "lastName":"Manager",
      "employeeId":"P69"
   },
   "employeeId":"P70"
}

2 个答案:

答案 0 :(得分:1)

您应该在不想包含的字段中使用@JsonIgnore注释。检查herehere了解更多信息。

答案 1 :(得分:0)

尝试使用延迟加载

@ManyToOne(fetch=FetchType.LAZY)