繁体   English   中英

使用具有关系的Spring Data REST发布实体

[英]Post an entity with Spring Data REST which has relations

我正在使用Spring Data Rest。 尝试使用关联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;
    //..
}

那么你可以用这样的addresses一个新User

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必须已经保留。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM