寒玉 Blog
  • Home
  • Books
  • About Me
  • Categories
  • Tags
  • Archives

Spring Boot 多对多注解


在使用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;
}

参考资料

  • http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

  • http://blog.csdn.net/maxu12345/article/details/45538157


  • « 概率论(机器学习)-贝叶斯公式
  • 概率论(机器学习)-朴素贝叶斯公式 »

Published

3 22, 2018

Last Updated

2018-03-22 12:04:53+08:00

Category

java

Tags

  • java 15
  • json 1
  • spring 2
  • spring-boot 1
  • Powered by Pelican. Theme: Elegant by Talha Mansoor