Spring boot,在双方的Json响应中包含一对多关系

问题描述 投票:0回答:1

我有两个实体,产品和类别,它们之间的关系为oneToMany。每个产品都有一个类别,一个仓库可以有多个产品。

我可以从类别侧显示JsonResponse中的产品列表,但是不是从产品方面。我想念什么?

-使用按categoryName获取类别时的-JsonResponse:

{
   "id": 1,
   "reference": "cat1",
   "name": "electornique",
   "produits": [
      {
         "id": 2,
         "reference": "tab1",
         "designation": "ordinateurupdate",
         "price": 600,
         "quantite": 1234
      },
      {
         "id": 3,
         "reference": "tel1",
         "designation": "tel 1 was updated",
         "price": 600,
         "quantite": 1234
      },
      {
         "id": 4,
         "reference": "ord2",
         "designation": "ordinateur",
         "price": 400,
         "quantite": 3
      }
   ]
}

使用按productReference获取产品时的JsonResponse:

URL:http://localhost:8080/api/produits/ord2

{
   "id": 4,
   "reference": "ord2",
   "designation": "ordinateur",
   "price": 400,
   "quantite": 3
}

我想实现这个目标:

{
   "id": 4,
   "reference": "ord2",
   "designation": "ordinateur",
   "price": 400,
   "quantite": 3,
   categorie : { id : "" , reference : "", name: "" }
}

-类别实体:

@Entity
@Table(name="categorie",indexes = {@Index (name="index_categorie_reference",columnList="reference",unique= true),
                                   @Index(name="index_categorie_name",columnList="name",unique= true)

})

public class Categorie implements Serializable {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String reference;

    @Column(unique= true)
    private String name;


    @OneToMany(mappedBy= "categorie")
    private List<Produit> produits;


// getters and setters...    

}

-产品实体:

@Entity
@Table(name="produit",indexes = {@Index (name="index_produit_reference",columnList="reference",unique= true)})
public class Produit  implements Serializable{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(unique = true)
  private String reference;

  private String designation;
  private double price;
  private int quantite;



  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="categorie_id") 
  @JsonIgnore
  private Categorie categorie;


  public Produit() {

  }


// getters and setters...   

}

java spring-boot one-to-many bidirectional
1个回答
0
投票

您看不到categorie属性,因为它用@JsonIgnore注释。

但是如果删除该注释,则序列化对象时将出现无限循环...Here是一篇有关可能的解决方案/解决方法的好文章。

© www.soinside.com 2019 - 2024. All rights reserved.