简体   繁体   English

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

[英]Spring-JPA - How to output limited fields from Self Joined tables

I have an entity named employee which has self join with itself.我有一个名为employee 的实体,它具有自我连接。 The join is to represent who is the manager for that employee.联接代表谁是该员工的经理。 When I query the records I am getting the whole hierarchy for the employee.当我查询记录时,我得到了员工的整个层次结构。

What I wish to achieve is to fetch only few fields of manager and do not wish to fetch an employee's manager's manager.我希望实现的是仅获取经理的几个字段,而不想获取员工的经理的经理。

I tried doing it using @NamedEntityGraph but not able to get the expected output.我尝试使用@NamedEntityGraph但无法获得预期的输出。 Used Projections as well.也使用Projections

I also tried the approach as mentioned here我也尝试了这里提到的方法

  1. JPA Self Join using JoinTable 使用 JoinTable 的 JPA 自联接

  2. Self join Spring JPA 自加入 Spring JPA

Note - I do not wish to use @Query annotation注意- 我不想使用@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;

}

Actual Result -实际结果 -

{
   "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"
}

Expected Result预期结果


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

You should use @JsonIgnore annotation in the fields you do not want to be included.您应该在不想包含的字段中使用@JsonIgnore注释。 Check here and here for more information.查看此处此处了解更多信息。

尝试使用延迟加载

@ManyToOne(fetch=FetchType.LAZY)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM