org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError)

前端 未结 5 695
余生分开走
余生分开走 2021-01-21 10:14

I am trying out some very basic webservice. I get this exception everytime I try to return the Prtnr object.

Uncaught exception thrown in one of the service met         


        
5条回答
  •  滥情空心
    2021-01-21 10:50

    In this link you can find how to solve this.

    However below I'll paste the solution in practice.

    It's very simple. Assuming that your database query already works without JSON, all you have to do is this:

    Add the @JsonManagedReference In the forward part of the relationship (i.e. User.java class):

    @Entity
    public class User implements java.io.Serializable{
    
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private long id;
    
     @Column(name="name")
     private String name;
    
     @ManyToMany
     @JoinTable(name="users_roles",joinColumns=@JoinColumn(name = "user_fk"),
     inverseJoinColumns=@JoinColumn(name = "role_fk"))
     @JsonManagedReference
     private Set roles = new HashSet();
    
    ...
    

    Add the @JsonBackReference In the back part of the relationship (i.e. Role.java class):

    @Entity
    public class Role implements java.io.Serializable {
    
     @Id 
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;
    
     @ManyToMany(mappedBy="roles")
     @JsonBackReference
     private Set users = new HashSet();
    
    ...
    

    The work is done. If you take a look at your firebug logs, you'll notice that the infinite recursive loop has disappeared.

提交回复
热议问题