0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use fetch = FetchType.EAGER instead of fetch = FetchType.LAZY.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.