我正在使用Spring Data Rest。我在尝试发布具有关联的对象时遇到问题(例如,address是我实体中的一个字段,该字段被映射为多个)。
问题是,我们应使用哪种格式将新实体与其关系联系起来。我看到了几个答案,并尝试了所有发现的选项。不幸的是,他们都不适合我。发生以下错误:
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; //.. }
那么你可以发布新的User与它addresses这样的:
User
addresses
POST http://localhost:8080/api/users { "name" : "user1", "addresses" : [ "http://localhost:8080/api/addresses/1", "http://localhost:8080/api/addresses/2" ] }
在发布新用户之前,地址ID#1和ID#2必须已经保留。