Hibernate OneToMany java.lang.StackOverflowError

后端 未结 10 985
傲寒
傲寒 2020-12-07 19:58

It\'s my first question here on stack, so please be gentle :D

I\'m trying to create hibernate OneToMany relationship. When I try to fetch some data from my DB, I\'m

10条回答
  •  無奈伤痛
    2020-12-07 20:51

    I had this error because I was parsing a list of objects mapped on both sides @OneToMany and @ManyToOne to json using jackson which caused an infinite loop.

    If you are in the same situation 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.

提交回复
热议问题