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
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);
}
}
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.
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 @JsonManagedReferenc
e 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.
You can annotate the second reference of Prtnr in PrtnrGeoInfoId with @JsonBackReference
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.