JSON加载惰性属性

JSON加载惰性属性,json,rest,spring-boot,spring-data-jpa,Json,Rest,Spring Boot,Spring Data Jpa,我有两个实体 产品: @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.LA

我有两个实体

产品:

 @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;
当我从RestController调用时,惰性关系被加载,但当我从主方法(springboot)调用时,它们变为空

当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"
    } ]
  }
} ]

图像必须为空,因为属性上的惰性配置

Json序列化程序将调用get方法,该方法将加载惰性字段。 如果不希望这些惰性字段出现在json中,可以在@JsonIgnore处对它们进行注释


@JsonInclude(JsonInclude.Include.NON_EMPTY)表示该字段只有在为空时才会被忽略。

使用
fetch=FetchType.EAGER
而不是
fetch=FetchType.LAZY

    [ {
  "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"
    } ]
  }
} ]