首页 > 解决方案 > Spring boot ,在双方的Json响应中包含一对多的关系

问题描述

我有两个实体,产品和类别,关系为 oneToMany 。每个产品都有一个类别,一个笼子可以有多个产品。

我可以从类别端显示 JsonResponse 中的产品列表,但不能从产品端显示。我错过了什么?

-JsonResponse 使用通过 categoryName 获取类别时:

{
   "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 :

网址: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...   

}

标签: javaspring-bootone-to-manybidirectional

解决方案


您看不到该categorie属性,因为它带有注释@JsonIgnore

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


推荐阅读