Can only create association from one side in Spring Data Rest

僤鯓⒐⒋嵵緔 提交于 2020-06-01 06:49:13

问题


@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"
}

works but

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

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.

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


EDIT: Added additional example page from https://www.baeldung.com/spring-data-rest-relationships

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

You cannot POST to http://localhost:8080/libraries/1


回答1:


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

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

Entities:

@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;
}

Request:

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

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

Result:

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


来源:https://stackoverflow.com/questions/61415740/can-only-create-association-from-one-side-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!