【问题标题】:JSON Loading Lazy propertiesJSON 加载延迟属性
【发布时间】:2017-12-28 16:37:30
【问题描述】:

我有 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 调用时正在加载惰性关系,但是当我从主方法(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"
    } ]
  }
} ]

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

【问题讨论】:

    标签: json rest spring-boot spring-data-jpa


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      Json 序列化程序将调用 get 方法,该方法将加载您的惰性字段。 如果您不想在 json 中使用这些惰性字段,您可以注释它们 @JsonIgnore。

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

      【讨论】:

        猜你喜欢
        • 2013-07-03
        • 2014-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多