只能在Spring Data Rest中从一侧创建关联 [英] Can only create association from one side in Spring Data Rest

查看:69
本文介绍了只能在Spring Data Rest中从一侧创建关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Entity
public class Product {
    //..
    private String name;

    @OneToMany(mappedBy = "product", orphanRemoval = true)
    private Set<File> files;
    //..
}

@Entity
public class File {
    //..
    @ManyToOne
    @JoinColumn(name = "product_id", nullable = true)
    Product product;
    //..
}

我只能从一侧创建关联,所以

I can only create the association from one side so

POST /files/{id}
{    
    "product" : "http://localhost:8080/api/products/1"
}

有效,但

POST /products/{id}
{    
    "files" : [
        "http://localhost:8080/api/files/1"
        ]
}

不起作用. POST不会返回任何错误,但不会建立关联,并且数据库也不会更新外键.

doesn't work. The POST doesn't return any error but the association is not made and the db doesn't update the foreign key.

根据此问题通过Spring发布实体具有关系的数据REST 应该可以,但是不能.

According to this question Post an entity with Spring Data REST which has relations it should work, but it doesn't.

https://www.baeldung.com/添加了其他示例页面春天数据休息关系

即使在该示例页面中,您也可以看到只能从许多"侧进行关联.在该示例中,他建立了Library-<-> Books一对多关系,并且唯一可以建立关联的关系如下:

Even in that sample page you can see that association can ever only be made from the "many" side. In that example, he made a Library<->Books One-To-Many relationship and the only you can make association is as follows:

curl -i -X PUT -H "Content-Type:text/uri-list"
-d "http://localhost:8080/libraries/1" http://localhost:8080/books/1/library

您无法发布到 http://localhost:8080/libraries/1

推荐答案

不幸的是,我想SDR现在不支持双向一对多.

I suppose that bi-directional one-to-many is not supported by SDR now, unfortunately.

只是尝试使用单向-to-many,并且工作正常:

I've just tried to use uni-directional one-to-many and it's working ok:

实体:

@Entity
class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany
    private List<Child> children;
}

@Entity
public class Child {
    @Id
    @GeneratedValue
    private Long id;

    private String name;
}

请求:

POST http://localhost:8080/parents
Content-Type: application/json

{
  "name": "parent1",
  "children": [
    "http://localhost:8080/children/1"
  ]
}

结果:

insert into parent (name, id) values ('parent1', 2);
insert into parent_children (parent_id, children_id) values (2, 1);

这篇关于只能在Spring Data Rest中从一侧创建关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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