我有类似的实体:
@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。
现在当我为id = 1的产品进行GET时,我从服务器上获取:
{
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]
}
使用Category
注释@JsonIdentityReference(alwaysAsId = true)
课程
通常工作,但当我提取一个或一个类别列表时,也只返回ids。只有在嵌入了类别时才需要ID转换。
谢谢!
答案 0 :(得分:0)
您只需在类别变量上使用@JsonIdentityReference(alwaysAsId = true)
。
E.g:
@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;
}