Could not write content: failed to lazily initialize a collection of role

后端 未结 9 1315
说谎
说谎 2021-02-08 02:48

I have One-To-Many relationship, here is my code

@Entity
@Table(name = \"catalog\")
public class Catalog {

    @Id
    @GeneratedValue(strategy = GenerationType         


        
9条回答
  •  独厮守ぢ
    2021-02-08 03:26

    It's caused by an infinite loop when parsing datas to JSON.

    You can solve this by using @JsonManagedReference and @JsonBackReference annotations.

    Definitions from API :

    • JsonManagedReference (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonManagedReference.html) :

      Annotation used to indicate that annotated property is part of two-way linkage between fields; and that its role is "parent" (or "forward") link. Value type (class) of property must have a single compatible property annotated with JsonBackReference. Linkage is handled such that the property annotated with this annotation is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling

    • JsonBackReference: (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonBackReference.html):

      Annotation used to indicate that associated property is part of two-way linkage between fields; and that its role is "child" (or "back") link. Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.

    Example:

    Owner.java:

    @JsonManagedReference
    @OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
    Set cars;
    

    Car.java:

    @JsonBackReference
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "owner_id")
    private Owner owner;
    

    Another solution is to use @JsonIgnore which will just set null to the field.

提交回复
热议问题