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

Java 如何避免Spring中一对一关系的无限循环?,java,spring,loops,Java,Spring,Loops,在我的申请中,我们在与有配偶的人打交道时遇到了一些困难,问题是每个人都可能有一个配偶,而这个配偶必须有这个人。如果你仔细想想,你会注意到这个关系创造了一个无限循环 通常我会通过在“配偶”属性中添加一个@JsonIgnore来解决这个问题,但我认为我们在请求中使用这个属性是因为我们使用Json来创建对象 我会尝试使用@JsonManagedReference和@JsonBackReference,但是只有一个类,类“person”,循环正在发生,因为这个类有它自己 还有其他注释我忘了吗?或者其他方

在我的申请中,我们在与有配偶的人打交道时遇到了一些困难,问题是每个人都可能有一个配偶,而这个配偶必须有这个人。如果你仔细想想,你会注意到这个关系创造了一个无限循环

通常我会通过在“配偶”属性中添加一个
@JsonIgnore
来解决这个问题,但我认为我们在请求中使用这个属性是因为我们使用Json来创建对象

我会尝试使用
@JsonManagedReference
@JsonBackReference
,但是只有一个类,类“person”,循环正在发生,因为这个类有它自己


还有其他注释我忘了吗?或者其他方法来解决此问题?

您需要使用
@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));       
打印输出:

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

如果在类中定义了属性
id
,则应该使用
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property=“id”)

或者,可以将其设置为
fetch=FetchType.LAZY
然后在查询中显式地加入并获取<代码>从个人p加入获取p配偶