【问题标题】:Can only create association from one side in Spring Data Rest只能在 Spring Data Rest 中从一侧创建关联
【发布时间】:2020-08-08 11:04:42
【问题描述】:
@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 不会更新外键。

根据这个问题Post an entity with Spring Data REST which has relations 它应该可以工作,但不能。


编辑:添加了来自 https://www.baeldung.com/spring-data-rest-relationships 的附加示例页面

即使在该示例页面中,您也可以看到只能从“多”端进行关联。在那个例子中,他建立了一个图书馆书籍一对多关系,你唯一可以建立的关联如下:

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

【问题讨论】:

    标签: spring hibernate spring-data spring-data-rest


    【解决方案1】:

    不幸的是,我认为 SDR 现在不支持双向一对多。

    just tried 使用单向一对多,它是 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);
    

    【讨论】:

    • 抱歉,不确定您的意思?它在这种情况下是否仅因为 Child 不引用 Parent 而起作用?
    • @erotsppa 实际上。双向一对多与关联实体没有对第一个引用的单向不同。由于需要同步关联的两端,双向 OTM 实现起来有点困难。你可以阅读更多关于它的信息here。而here 你可以找到 SDR 作者 Oliver Drotbohm 关于不使用双向 OTM 的建议...
    猜你喜欢
    • 2017-08-26
    • 2016-11-29
    • 1970-01-01
    • 2019-12-25
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多