Could not write content: failed to lazily initialize a collection of role

后端 未结 9 1311
说谎
说谎 2021-02-08 02:48

I have One-To-Many relationship, here is my code

@Entity
@Table(name = \"catalog\")
public class Catalog {

    @Id
    @GeneratedValue(strategy = GenerationType         


        
相关标签:
9条回答
  • 2021-02-08 03:37

    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;
    } 

    0 讨论(0)
  • 2021-02-08 03:38

    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;
    }
    
    0 讨论(0)
  • 2021-02-08 03:48

    "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

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