Post 具有关系的 Spring 数据 REST 的实体
Post an entity with Spring Data REST which has relations
我正在使用 Spring 数据休息。我在尝试 POST 具有关联的对象时遇到问题(例如,地址是我实体中的一个字段,它被映射为多对一)。
问题是,我们应该使用什么格式来连接我们的新实体及其关系。我看到了几个答案并尝试了我找到的所有选项。不幸的是,所有这些都不适合我。
发生以下错误:
Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ADDRESS_ID"; SQL statement:
JSON 我试过:
{
"name": "test",
"email": "test@email",
"address": "http://localhost:8080/MyApp/address/1"
}
还尝试了这些:
"address": {"id":"http://localhost:8080/MyApp/address/1"}
还有这个:
"address":{"id":1}
甚至这个:
"address": {
"href": "http://localhost:8080/MyApp/address/1"
}
有没有办法做到这一点,或者只为 POST 编写自己的控制器实现?谢谢!
如果您有这样的模型:
@Entity
public class User {
//..
private String name;
@OneToMany(mappedBy = "user")
private Set<Address> addresses = new HashSet<>();
//..
}
@Entity
public class Address {
//..
@ManyToOne
private User user;
//..
}
然后你可以 POST 一个新的 User
和它的 addresses
像这样:
POST http://localhost:8080/api/users
{
"name" : "user1",
"addresses" : [
"http://localhost:8080/api/addresses/1",
"http://localhost:8080/api/addresses/2"
]
}
在 POST 新用户之前,地址 ID#1 和 ID#2 必须已经保存。
我正在使用 Spring 数据休息。我在尝试 POST 具有关联的对象时遇到问题(例如,地址是我实体中的一个字段,它被映射为多对一)。
问题是,我们应该使用什么格式来连接我们的新实体及其关系。我看到了几个答案并尝试了我找到的所有选项。不幸的是,所有这些都不适合我。 发生以下错误:
Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ADDRESS_ID"; SQL statement:
JSON 我试过:
{
"name": "test",
"email": "test@email",
"address": "http://localhost:8080/MyApp/address/1"
}
还尝试了这些:
"address": {"id":"http://localhost:8080/MyApp/address/1"}
还有这个:
"address":{"id":1}
甚至这个:
"address": {
"href": "http://localhost:8080/MyApp/address/1"
}
有没有办法做到这一点,或者只为 POST 编写自己的控制器实现?谢谢!
如果您有这样的模型:
@Entity
public class User {
//..
private String name;
@OneToMany(mappedBy = "user")
private Set<Address> addresses = new HashSet<>();
//..
}
@Entity
public class Address {
//..
@ManyToOne
private User user;
//..
}
然后你可以 POST 一个新的 User
和它的 addresses
像这样:
POST http://localhost:8080/api/users
{
"name" : "user1",
"addresses" : [
"http://localhost:8080/api/addresses/1",
"http://localhost:8080/api/addresses/2"
]
}
在 POST 新用户之前,地址 ID#1 和 ID#2 必须已经保存。