1

I have entities like those:

@Entity
public Product {
   @Id
   public int id;

   public String name;

   @ManyToOne(cascade = {CascadeType.DETACH} )
   Category category

   @ManyToMany(cascade = {CascadeType.DETACH} )
   Set<Category> secondaryCategories;


}

and

@Entity
public Category {
   @Id
   public int id;

   public String name;

    @JsonCreator
    public Category(int id) {
        this.id = id;
    }

    public Category() {}
}

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.

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

is it possible to get back:

{ 
  id: 1,
  name: "product 1", 
  category: 2, 
  secondaryCategories: [3, 4, 5]
}

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.

Thanks!

Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106

1 Answers1

0

You need to use @JsonIdentityReference(alwaysAsId = true) on the category variable only.

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;


}
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45