首页 > 解决方案 > 如何同时添加响应ID和加入对象

问题描述

我想同时响应 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
  }
}

标签: javaspringspring-boot

解决方案


您需要将此列标记为不可插入且不可更新。另一件事是将此属性的 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();
}

推荐阅读