Json (fasterxml) stackoverflow exception

不打扰是莪最后的温柔 提交于 2019-12-05 10:50:36

Probably if you comment private Category parent; you will not have the StackOverflow. I've got the same problem in a project with circular dependencies.

The best way to solve this problem is to use the id of the parent instead of the Class like:

private Long parentId;

Edit:

The problem is with getParentChain() that is trying to be serialized. By adding @JsonIgnore before the method the problem was resolved.

Sure thing, @JsonIgnore does the job. But what if we need ignored field in our JSON output?

The solution is very simple.

We annotate our 'guilty' field by @JsonManagedReference annotation on the one side of our relation (which means our @ManyToMany annotation).

And @JsonBackReference on the other side of relation (where @OneToMany has been placed).

And that's it. No more recursive loops.

One annotation solves your problem.

Add following annotation on class.

@JsonIdentityInfo(
      generator = ObjectIdGenerators.PropertyGenerator.class, 
      property = "id")

Other way is to annotate on Collections @JsonManagedReference for forward direction and @JsonBackReference. for backward direction in mapping.

example:

public class User{
    @JsonManagedReference
    @OneToMany(mappedBy = "user")
    Set<Address> s = new Hashset<>();
}

public class Address{
    @JsonBackReference
    @ManyToOne
    @JoinColumn
    User user;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!