single custom serializer for all embedded annotated objects that replaces them with their ids(所有嵌入式注释对象的单个自定义序列化程序,用它们的 id 替换它们)
问题描述
我有这样的实体:
@Entity
public Product {
@Id
public int id;
public String name;
@ManyToOne(cascade = {CascadeType.DETACH} )
Category category
@ManyToMany(cascade = {CascadeType.DETACH} )
Set<Category> secondaryCategories;
}
和
@Entity
public Category {
@Id
public int id;
public String name;
@JsonCreator
public Category(int id) {
this.id = id;
}
public Category() {}
}
是否可以仅注释 Category 类或 category 和 secondaryCategories 属性,并使用注释将它们序列化为它们的 id当它们被嵌入时.
is it possible to annotate either just Category class or category and secondaryCategories properties with an annotation that will serialize them to be just their ids when they are embedded.
现在,当我为 id=1 的产品创建 GET 时,我正在从服务器获取信息:
right now I am getting from the server when I make a GET for product with id=1:
{
id: 1,
name: "product 1",
category: {id: 2, name: "category 2" },
secondaryCategories: [{id: 3, name: "category 3" },
{id: 4, name: "category 4" },
{id: 5, name: "category 5" }]
}
有没有可能回来:
{
id: 1,
name: "product 1",
category: 2,
secondaryCategories: [3, 4, 5]
}
使用 @JsonIdentityReference(alwaysAsId = true) 注释 通常工作,但当我获取一个或一个类别列表时也只返回 ids.只有在嵌入 Category 时才需要 id 转换.Category 类
Annotating Category class with @JsonIdentityReference(alwaysAsId = true)
works generally but also returns just ids when I am fetching one or a list of Categories. I need id conversion only when Category is embedded.
谢谢!
推荐答案
您只需要在类别变量上使用 @JsonIdentityReference(alwaysAsId = true).
You need to use @JsonIdentityReference(alwaysAsId = true) on the category variable only.
例如:
@Entity
public Product {
@Id
public int id;
public String name;
@ManyToOne(cascade = {CascadeType.DETACH} )
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Category.class)
@JsonIdentityReference(alwaysAsId = true)
Category category;
@ManyToMany(cascade = {CascadeType.DETACH} )
Set<Category> secondaryCategories;
}
这篇关于所有嵌入式注释对象的单个自定义序列化程序,用它们的 id 替换它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:所有嵌入式注释对象的单个自定义序列化程序,用它们的 id 替换它们
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
