我在MySQL中有两个简单的表格
User ---(one-to-many)--- Expense
我正在使用Spring JPA生成这两个实体。Expense有一个'user_id'外键字段,它引用了User表中的'id'字段。
我在请求中使用JSON来填充表格。
User
{"id":1, "username":"user"}
Expense
{
"id":1,
"user_id":1, <--- this value is not null in MySQL
"expense":"expense"
}
调用API时,我已经有了user_id的值,而且我不想传递整个对象。
有没有一种方法可以告诉Spring,这是一个引用"User"表中"id"列的INTEGER FOREIGN KEY?
我在网上找到的所有示例都只展示了如何通过在JSON中传递整个"User"对象来实现。
我的当前实现:
@Entity
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private int id;
private String username;
}
@Entity
public class Car{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private int id;
@ManyToOne
private User user_id;
private String expense;
}