单个自定义序列化程序,用于所有嵌入的带注释的对象,用它们的id替换它们 [英] single custom serializer for all embedded annotated objects that replaces them with their ids

查看:92
本文介绍了单个自定义序列化程序,用于所有嵌入的带注释的对象,用它们的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() {}
}

是否可以注释类别类或类别 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的产品:

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]
}

使用<$注释类别类c $ c> @JsonIdentityReference(alwaysAsId = true)
通常有效但在我提取一个或一个类别列表时也只返回ids。我只在嵌入类别时才需要转换。

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替换它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆