I have One-To-Many relationship, here is my code
@Entity
@Table(name = \"catalog\")
public class Catalog {
@Id
@GeneratedValue(strategy = GenerationType
Using FetchType.LAZY , if still getting the error "Could not write content: failed to lazily initialize a collection of role" , that may be probably caused by somewhere in the logic (perhaps in a controller) , Catalog is being tried to be deserialized that contains list of catalog items which is a proxy but the transaction has already ended to get that. So create a new model ('CatalogResource' similar to catalog but without the list of items). Then create a catalogResource object out of the Catalog (which is returned from the query)
public class CatalogResource {
private int catalog_id;
private String name;
private List<Order> orders;
}
Here is my solution for this task with Hibernate. I marked hibernate releation with @JsonIgnore and use custom field for jackson, in which I check if the field is loaded. If you need serialize collection to json then you should manualy call collection getter during hibernate transaciton.
@JsonIgnore
@OneToMany(mappedBy = "myorder")
private List<OrderItem> orderItems = new ArrayList<>();
@JsonProperty(value = "order_items", access = JsonProperty.Access.READ_ONLY)
private List<OrderItem> getOrderItemsList() {
if(Hibernate.isInitialized(this.relatedDictionary)){
return this.relatedDictionary;
} else{
return new ArrayList<>();
}
}
@JsonProperty(value = "order_items", access = JsonProperty.Access.WRITE_ONLY)
private void setOrderItemsList(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
"You don't serialize in your JSON the children entities by using the com.fasterxml.jackson.annotation.JsonIgnore
property"
Add @JsonIgnore
for hibernate lazy loading properties eg. @ManyToOne
. That should work