Java 如何使用Spring Boot 2处理Spring数据JPA中的自引用?

Java 如何使用Spring Boot 2处理Spring数据JPA中的自引用?,java,spring-boot,spring-data-jpa,jackson,self-referencing-table,Java,Spring Boot,Spring Data Jpa,Jackson,Self Referencing Table,我有一个Spring Boot 2应用程序,其中有以下用户实体: @Data ... JPA and other annotations class User { ... many fields including Integer id @ManyToOne(fetch = FetchType.LAZY) public User createBy; @ManyToOne(fetch = FetchType.LAZY) public User updateB

我有一个Spring Boot 2应用程序,其中有以下用户实体:

@Data
... JPA and other annotations
class User {
    ... many fields including Integer id
    @ManyToOne(fetch = FetchType.LAZY)
    public User createBy;
    @ManyToOne(fetch = FetchType.LAZY)
    public User updateBy;
}
现在,我现在面临的主要问题是用户的自引用(来自用户),这会导致StackOverflow异常或InvalidDefinitionException,具体取决于我对用户使用的特定注释。这一问题非常常见,互联网上讨论了几种解决方案,包括:

1。用@JsonBackReference注释这两个字段 使用@JsonBackReference进行注释会完全忽略updateBy和createBy字段,这意味着我无法在API响应中获得它们

2。用@jsonidentialinfo(generator=ObjectIdGenerators.PropertyGenerator.class,property=“id”)或None.class或IntSequenceGenerator.class或UUIDGenerator.class注释类 这种方法可以很好地工作,直到序列化程序在json的某个地方找到相同的用户对象,它不再将其放在那里,而是根据上面选择的类放置该对象的引用。e、 g

[
  {"id": 1, ..., "createBy": {"id": 2, ...},
  2 // <- Let's ignore how user 1 is created by user 2 and notice that instead of a user object, I get an integer ID reference.
]
  • 当客户端发送一个用户对象作为请求主体时,应用程序只需要子实体的id,而不需要整个对象,如下所示:
  • 我知道自引用是ORMs不可或缺的一部分,并且有很多自引用的用例。但是专业开发人员/应用程序如何处理这个问题,特别是在Spring框架中?如果自定义序列化程序是唯一的方法,那么如何使其正常工作

    另外,建议从EqualsAndHashCode和ToString方法中排除这些字段(createBy和updateBy)吗

    {
      "id": 1, "name": "old user", .. many other fields .., "createBy": {id: 2, "name": "2nd user"}
    }
    
    {
       "name": "new user", ...., "createBy": {id: 1}
    }