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

前端 未结 5 681
余生分开走
余生分开走 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:46

    this is a general serializing issue. you have to break those dependencies using @Transient while writing to xml or json or object stream.

    and you have to wire them back while reading. wiring is done in such method

    class Way{
    list nodes;
    addNode(Node node){
    node.setWay(this);
    nodes.add(node);
    

    }

    }
    
    0 讨论(0)
  • 2021-01-21 10:49

    The infinite recursion is due to the following: Class Prtnr contains Set<PrtnrGeoInfo> prtnrGeoInfos and each PrtnrGeoInfo contains PrtnrGeoInfoId id which in turn contains Prtnr partner.

    Thus, Prtnr -> PrtnrGeoInfo ->PrtnrGeoInfoId ->Prtnr, is causing a cyclic dependency which is a problem for Jackson when it is trying to do the POJO Mapping.

    You need to remove this cyclic dependency to fix this exception.

    0 讨论(0)
  • 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<Role> roles = new HashSet<Role>();
    
    ...
    

    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<User> users = new HashSet<User>();
    
    ...
    

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

    0 讨论(0)
  • 2021-01-21 10:53

    You can annotate the second reference of Prtnr in PrtnrGeoInfoId with @JsonBackReference

    0 讨论(0)
  • 2021-01-21 11:02

    This is quite a common scenario for me when you are trying to convert entity classes into JSON format. The simplest solution is just to use @JsonIgnore on the reverse mapping to break the cycle.

    0 讨论(0)
提交回复
热议问题