Search code examples
jsonspringjackson

Jpa entity relationship caused endless loop


I am using spring data jpa to build my project. There is a User entity and a Biz entity.

@ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private UserInformation belongUser;//所属用户

This code above is part of Biz class.

@OneToMany(cascade = CascadeType.ALL,mappedBy = "belongUser")
private Set<BizInformation> bizs = new HashSet<BizInformation>();

And this is part of User class

The Problem is when I get a UserInfomation via RESTful api, it returns a BizInfo,then inside the BizInfo it returns the UserInfomation,and finally caused a StackOverFlow Exception.

How can I solve this? thanks.


Solution

  • This problem cause by the bidirectional relationships. you can use @JsonManagedReference and @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.

    in your case you can add @JsonManagedReference in User class

    @OneToMany(cascade = CascadeType.ALL,mappedBy = "belongUser")
    @JsonManagedReference
    private Set<BizInformation> bizs = new HashSet<BizInformation>();
    

    and @JsonBackReference for Biz class which will omit the UserInformation serialization

    @ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    @JsonBackReference
    private UserInformation belongUser;//所属用户
    

    you can also use @JsonIgnore for the class that you want to omit the serialization

    more detail : jackson-bidirectional-relationships-and-infinite-recursion