【问题标题】:jpa lazy return all elementjpa 懒惰返回所有元素
【发布时间】:2015-06-26 02:34:33
【问题描述】:

我有两个班级品牌和型号。我使用延迟加载。

@Entity
public class Brand {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long brandId;

  private String brand;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "brand")
  @JsonManagedReference
  private List<Model> modelList;
  ...
}

@Entity
public class Model {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long modelId;

  private String model;

  @ManyToOne
  @JoinColumn(name = "brandId")
  @JsonBackReference
  private Brand brand;
  ...
}

在我的存储库中,我使用标准方法 findAll。

public interface BrandRepository extends JpaRepository<Brand, Long>

当我打电话获取品牌时

卷曲http://localhost:8080/brands

我也有模特

[
{
“品牌标识”:1, “品牌”:“丰田”, “模型列表”:[
{
“型号”:1, “模型”:“回声” }, {
“型号”:2, “型号”:“卡罗拉” } ] }, {
“品牌标识”:2, “品牌”:“本田”, “模型列表”:[
{
“型号”:3, “模型”:“公民” }, {
“型号”:4, “型号”:“雅阁” } ] }, {
“品牌标识”:3, “品牌”:“起亚”, “模型列表”:[
{
“型号”:5, “模型”:“索兰托” } ] }, {
“品牌标识”:4, “品牌”:“福特”, “模型列表”:[
{
“型号”:6, “模型”:“野马” } ] } ]

有什么遗漏吗?

【问题讨论】:

    标签: spring-data spring-data-jpa jpa-2.1


    【解决方案1】:

    如果你想从Brand 中省略模型,你应该把@JsonBackReference 放在modelList 上而不是@JsonManagedReference

    @JsonManagedReference 是引用的前向部分——正常序列化的部分。

    @JsonBackReference 是引用的后面部分——它将从序列化中省略。

    希望这会有所帮助。

    【讨论】:

    • 那行得通,@@JsonBackReference 在 Brand 类中,@@JsonManagedReference 在模型类中
    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2013-12-22
    相关资源
    最近更新 更多