我有2个实体
产品:
@Id @GeneratedValue
private Long id;
private String name;
private String description;
@ManyToOne(fetch = FetchType.LAZY)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Product parentProduct;
@OneToMany(fetch = FetchType.LAZY)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Set<Product> childProduct;
@OneToMany(mappedBy="product", fetch = FetchType.LAZY)
@JsonManagedReference @JsonInclude(JsonInclude.Include.NON_EMPTY)
private Set<Image> images;
图片:
@Id
@GeneratedValue
private Long id;
private String type;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JsonBackReference
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Product product;
当我从RestController调用时,正在加载惰性关系,但是当我从我的main方法(Spring Boot)调用时,它们变空了。
当Json序列化时,我做了什么来保持懒惰。
json回归:
[ {
"id" : 1,
"name" : "Passatempo Pacote",
"description" : "Cookies Package",
"images" : [ {
"id" : 2,
"type" : "png"
}, {
"id" : 1,
"type" : "jpeg"
} ]
}, {
"id" : 2,
"name" : "Passatempo",
"description" : "Cookies",
"parentProduct" : {
"id" : 1,
"name" : "Passatempo Pacote",
"description" : "Cookies Package",
"images" : [ {
"id" : 2,
"type" : "png"
}, {
"id" : 1,
"type" : "jpeg"
} ]
}
} ]
图片必须为空,因为属性上的延迟配置
答案 0 :(得分:1)
Json Serializer将调用get方法,该方法将加载您的惰性字段。 如果你不想在json中使用这些惰性字段,你可以注释它们@JsonIgnore。
@JsonInclude(JsonInclude.Include.NON_EMPTY)表示仅当字段为空时才会忽略该字段。
答案 1 :(得分:0)
使用fetch = FetchType.EAGER
代替fetch = FetchType.LAZY
。