在Spring Data Rest中只能从一侧创建关联。

问题描述 投票:0回答:1
@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;
    //..
}

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

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

工作但

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

不起作用。POST没有返回任何错误,但是关联没有建立,db也没有更新外键。

根据这个问题 用Spring Data REST发布一个实体,该实体有以下关系。 它应该工作,但它没有。


EDIT: 添加了额外的示例页面,来自 https:/www.baeldung.comspring-data-rest-relationships

即使在那个示例页中,你也可以看到,永远只能从 "多 "方面进行关联。在那个例子中,他做了一个Library<->Books One-To-Many的关系,而你唯一可以做关联的是如下。

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

你不能POST到 http:/localhost:8080libraries1。

spring hibernate spring-data spring-data-rest
1个回答
0
投票

我想,很遗憾,现在SDR不支持双向的一对多。

我已经 刚试过 使用单方向的一对多,它的。好用:

负责部门:实体。

@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);
© www.soinside.com 2019 - 2024. All rights reserved.