java - 如何同时添加响应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
}
}
解决方案
您需要将此列标记为不可插入且不可更新。另一件事是将此属性的 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();
}
推荐阅读
- php - 尝试用两个可能的外键定义关系
- sql - 在 PostgreSQL 中除以两个运行总计
- listagg - 在 Orcale 中使用 LISTAGG - ORA-00937:不是单组组函数
- java - RabbitMQ 错误 java.util.concurrent.TimeoutException: null
- python - 拆分python pandas Dataframe中列的内容并使用新分离的字符串列表创建一个新的Dataframe
- c++ - 应用程序在将数据上传到数据库之前关闭,Qt
- ruby-on-rails - 部署成功后active_admin登录失败
- python-3.x - 即使错误停止,Python 日志记录也会继续写入文件
- python - Python:mupdf:dict中的无效键
- javascript - 如何使用 Tailwind CSS 创建左侧固定部分和右侧可滚动部分的 div?