在使用spring boot开发的时候,经常出现多对多的情况,在进行序列化的时候,如果不处理,就会出现StackOverflowError的异常.这时候需靠考虑使用Jackson的几个注解处理了问题.
JsonManagedReference
和JsonManagedReference
例如下面的例子:
User entity:
public class User {
public int id;
public String name;
@JsonBackReference
public List<Item> userItems;
}
Item entity:
public class Item {
public int id;
public String itemName;
@JsonManagedReference
public User owner;
}
测试代码:
@Test
public void
givenBidirectionRelation_whenUsingJacksonReferenceAnnotation_thenCorrect()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
输出结果
{
"id":2,
"itemName":"book",
"owner":
{
"id":1,
"name":"John"
}
}
所以使用注解JsonManagedReference和JsonBackReference可以解决循环序列化的问题
-
@JsonManagedReference is the forward part of reference – the one that gets serialized normally
-
@JsonBackReference is the back part of reference – it will be omitted from serialization.
@JsonBackReference
和@JsonManagedReference
通常配对使用.通常用在父子关系中.
@JsonBackReference
标注在属性序列化的时候,会被忽略.JsonManagedReference标注的属性会被序列化.
@JsonIgnore
直接忽略属性.
自关联的实体类使用MangToOne和OneToMany来自映射
@Entity
public class Category {
@ManyToOne
private Category parent;
@OneToMany(mappedBy="parent")
private Set<Category> children;
}