Reputation: 1
I have 2 entities
Product:
@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;
Image:
@Id
@GeneratedValue
private Long id;
private String type;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JsonBackReference
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Product product;
the lazy relationship are being loaded when I call from a RestController but when I call from my main method (Spring Boot) they came empty.
What I do to maintain lazy when Json serialize.
json return:
[ {
"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"
} ]
}
} ]
Images must be empty because lazy config on property
Upvotes: 0
Views: 506
Reputation: 2597
Use fetch = FetchType.EAGER
instead of fetch = FetchType.LAZY
.
Upvotes: 0
Reputation: 85
The Json Serializer will call the get method, which will load your lazy field. If you don't want these lazy field in json, you could annotate them @JsonIgnore.
@JsonInclude(JsonInclude.Include.NON_EMPTY) means the field will be ignored only if it's empty.
Upvotes: 1