Java 如何使用Spring Boot 2处理Spring数据JPA中的自引用?
我有一个Spring Boot 2应用程序,其中有以下用户实体: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
@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": 1, "name": "old user", .. many other fields .., "createBy": {id: 2, "name": "2nd user"}
}
{
"name": "new user", ...., "createBy": {id: 1}
}