关于java:JsonManagedReference与JsonBackReference

JsonManagedReference vs JsonBackReference

我想知道杰克森的@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.

所以他们真的取决于你们关系的方向

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class User {
    public int id;
    public String name;

    @JsonBackReference
    public List<Item> userItems;
}

public class Item {
    public int id;
    public String itemName;

    @JsonManagedReference
    public User owner;
 }


@JsonManagedReference@JsonBackReference用于处理字段之间的双向链接,一个用于父角色,另一个用于子角色。

For avoiding the problem, linkage is handled such that the property
annotated with @JsonManagedReference annotation is handled normally
(serialized normally, no special handling for deserialization) and the
property annotated with @JsonBackReference annotation is not
serialized; and during deserialization, its value is set to instance
that has the"managed" (forward) link.


我更喜欢@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property ="id", scope = Long.class)。其中,property是主键字段的名称,scope是它的类型


  • @jsonManagedReference->管理引用的前向部分,此注释标记的字段是序列化的字段。
  • @jsonbackreference->管理引用的反向部分,用此注释标记的字段/集合没有序列化。

用例:您的实体/表中有一个多个或多个关系,如果不使用上面的关系,将导致错误,例如

1
Infinite Recursion and hence stackoverflow - > Could not write content: Infinite recursion (StackOverflowError)

发生上述错误是因为Jackson(或其他类似的人)试图对关系的两端进行序列化并以递归结束。

@JSonignore执行类似的函数,但最好使用上面提到的注释。