如何同时添加响应ID和加入对象

时间:2019-05-19 20:15:20

标签: java spring spring-boot

我想同时响应2个值:

  @Column(name = "category_id")
  private int categoryId;

  @OneToOne
  @JoinColumn(name = "category_id")
  private Category category;

第一个只是类别的ID,第二个是此ID的嵌套对象。

{
  "id": 1,
  "productName": "Product HHYDP",
  "categoryId": 1,
  "unitInStock": 23,
  "unitPrice": 18,
  "category": {
    "id": 1,
    "categoryName": "Beverages",
    "description": "Soft drinks, coffees, teas, beers, and ales",
    "picture": null
  }
}

1 个答案:

答案 0 :(得分:1)

您需要将此列标记为不可插入且不可更新。 另一件事是将此属性的getter实现为类别ID的返回值。

@Column(name = "category_id", insertable=false, updatable=false)
@JsonProperty(value="categoryId")
private int categoryId;

@OneToOne
@JoinColumn(name = "category_id")
private Category category;

public int getCategoryId(){
    return category.getId();
}