I'm implementing a RESTful service using Spring Framework v3.2.4 and JPA + Hibernate 4. I'm returning resources in JSON format (using Jackson Mapper), but now I'm stuck with this exception:
Could not write JSON: failed to lazily initialize a collection of role: it.teck.service.model.Canvas.params, could not initialize proxy - no Session (through reference chain: it.teck.service.model.Canvas["params"]);
I have a "many to many" relationship between Canvas
and Param
entities and I need to serialize also params list when a canvas is requested to the service.
In my classes I have:
@Entity
public class Canvass {
@ManyToMany
@JoinTable(name = "canvas_params", joinColumns = { @JoinColumn(name = "id_canvas", referencedColumnName = "id_canvas") }, inverseJoinColumns = { @JoinColumn(name = "id_param", referencedColumnName = "id_param") })
private List<Param> params;
// ...
}
And:
@Entity
public class Param {
@ManyToMany(mappedBy = "params")
private List<Canvas> canvasList;
// ...
}
In several posts and SO answers is suggested to exclude ManyToMany
fields from serialization, to break the serialization loop, but I need to serialize params linked to my canvas entities. So, what should I do?