使用Spring Data REST发布具有关系的实体 [英] Post an entity with Spring Data REST which has relations

查看:97
本文介绍了使用Spring Data REST发布具有关系的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Data Rest.我在尝试发布具有关联的对象时遇到问题(例如,address是我实体中的一个字段,该字段最多映射到一个).

I'm using Spring Data Rest. I have a problem trying to POST an object with association(e.g. address is a field in my entity that is mapped as many to one).

问题是,我们应使用哪种格式将新实体与其关系联系起来.我看到了几个答案,并尝试了所有发现的选项.不幸的是,他们都不适合我. 发生以下错误:

The question is, what format should we use to connect our new entity with its relations. I saw several answers and tried all options that I found. Unfortunately, all of them don't work for me. The following error happens:

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编写自己的控制器实现?谢谢!

Is there a way to do this, or only writing own implementation of controller for POST? Thanks!

推荐答案

如果您有这样的模型:

@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:

then you can POST a new User with its addresses like this:

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

Before POST a new User, addresses ID#1 and ID#2 must be already persisted.

这篇关于使用Spring Data REST发布具有关系的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆