java - 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...
}
解决方案
您看不到该categorie
属性,因为它带有注释@JsonIgnore
。
但是,如果删除该注释,则在序列化对象时将出现无限循环…… 这是一篇关于可能的解决方案/解决方法的好文章。
推荐阅读
- unity3d - Unity 2017.3 构建资产包需要很长时间
- c++ - 可以采用 Eigen::vector 或 std::vector 的 C++ 模板函数
- mysql - Laravel MySQL 搜索。允许用户进行自定义布尔搜索
- c# - Unity 2D - 导致疯狂延迟的程序(字符串代码)
- sql-server - SQL Server 查询每一行
- dependency-injection - Google Guice 每次都返回新实例
- python - 如何在标签中同时显示图片和文字?(PyQt)
- c# - 是否可以通过 `dotnet` CLI 命令将文件添加到项目中?
- javascript - $未定义,js中没有def错误
- android - Appcelerator Titanium 中的自定义通知视图