I have the following issue with lazy initialization and serialization with Gson API: here is my entities:
Here is the first entity:
public class Cable implements Serializable {
/**
* serialVersionUID used for the serialization
*/
private static final long serialVersionUID = 9144466650131822647L;
@Id
@Column(name = "reference_cab")
private String rexelReference;
@Column(name = "reference_fab")
private String providerReference;
@Column(name = "libelle")
private String productLibe;
@JsonIgnore
@ManyToMany(mappedBy = "cables", fetch = FetchType.LAZY)
private Collection<CrossSelling> complementaryProducts = new ArrayList<CrossSelling>();
Here is the second entity:
public class CrossSelling implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String reference;
@JsonIgnore
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "cable_complementaryproduct", joinColumns = { @JoinColumn(name = "reference", referencedColumnName = "reference") }, inverseJoinColumns = { @JoinColumn(name = "reference_cab", referencedColumnName = "reference_cab") })
private Collection<Cable> cables = new ArrayList<Cable>();
@Column
private String designation;
I tried to fetch complementaryproducts data lazily using fetch join using this query:
select distinct cable from Cable cable left join fetch cable.complementaryProducts
I have a service calling this query called display:
In my web service I do the following:
final Gson gson = new Gson();
return new ResponseEntity<Object>(gson.toJson(this.shoppingCartService.display()), HttpStatus.OK);
But I have the following issue:
failed to lazily initialize a collection of role: com.sso.uuu.model.CrossSelling.cables, could not initialize proxy - no Session] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.sso.uuu.model.CrossSelling.cables, could not initialize proxy - no Session
It is working well wihtou gson.toJson(), but because we have an encoding issue, we need to use it Thank you for your Help.