简体   繁体   English

如何避免 Spring 中一对一关系的无限循环?

[英]How to avoid infinite loop with One-To-One relationship in Spring?

In my application we are having some trouble dealing with people with spouse, the problem is that each person may have a spouse, and this spouse will have to have this person.在我的申请中,我们在与有配偶的人打交道时遇到了一些麻烦,问题是每个人都可能有一个配偶,而这个配偶必须有这个人。 If you think close about it you will notice that this relation creates a infinite loop.如果您仔细考虑它,您会注意到这种关系创建了一个无限循环。

Normally I would resolve this by putting a @JsonIgnore at the "spouse" attribute, but I we use this attribute in our requests because we use Json's to create the object.通常我会通过在“配偶”属性中@JsonIgnore来解决此问题,但我在请求中使用此属性,因为我们使用 Json 来创建 object。

I would try to use @JsonManagedReference and @JsonBackReference , but there's just one class, the class "person", the loop is happening because this class has itself.我会尝试使用@JsonManagedReference@JsonBackReference ,但只有一个 class,即 class “人”,循环正在发生,因为这个 class 有它自己。

Is there other annotation that I'm forgetting?还有其他我忘记的注释吗? or other way to fix this?或其他方法来解决这个问题?

You need to use @JsonIdentityInfo annotation:您需要使用@JsonIdentityInfo注释:

@Getter
@Setter
@AllArgsConstructor
@ToString
@JsonIdentityInfo(generator= ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class Person {
    private final String name;
    private final int age;
    private final String address;

    private Person spouse;
    
    public boolean isMarried() {
        return null != spouse;
    }
}

// test
ObjectMapper mapper = new ObjectMapper();

Person john = new Person("john", 28, "London", null);
Person gill = new Person("gill", 24, "London", null);
john.setSpouse(gill);
gill.setSpouse(john);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(john));       

Output printed: Output 印刷:

{
  "@id" : 1,
  "name" : "john",
  "age" : 28,
  "address" : "London",
  "spouse" : {
    "@id" : 2,
    "name" : "gill",
    "age" : 24,
    "address" : "London",
    "spouse" : 1,
    "married" : true
  },
  "married" : true
}

If you have property id defined inside your class, you should use @JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id") .如果您在 class 中定义了属性id ,则应使用@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")

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

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