我有此映射用户* ----------- 1 Sexe
public class User {
@ManyToOne
@JoinColumn(name="sexe_id")
private Sexe sexe;
// Rest of the Attributes
}
public class Sexe {
@OneToMany(mappedBy="sexe", fetch = FetchType.LAZY)
private List<User> users;
// Rest of the Attributes
}
和休息呼叫控制器
@GetMapping("/users")
public List<User> getAllUsers()
{
System.out.println("Get all Users...");
List<User> users = new ArrayList<>();
userRepository.findAll().forEach(users::add);
return users;
}
使用邮递员后,出现此异常:
at
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
~[jackson-databind-2.9.6.jar:2.9.6] at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:145)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:107)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
~[jackson-databind-2.9.6.jar:2.9.6] at
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
~[jackson-databind-2.9.6.jar:2.9.6] at
在谷歌搜索之后,我发现解决方案是使用@JsonIgnore
。
这个注释解决了我的问题。但是,使用此注释会导致角度问题。
请您提出其他建议以避免这种例外情况?非常感谢您的帮助。
答案 0 :(得分:0)
JsonIgnore
不是唯一的解决方案。您还可以使用@JsonManagedReference
和@JsonBackReference
@ManyToOne
@JsonBackReference
@JoinColumn(name="sexe_id")
private Sexe sexe;
@JsonManagedReference
@OneToMany(mappedBy="sexe", fetch = FetchType.LAZY)
private List<User> users;
请参见Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot