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;
    //..
}

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

erotsppa
  • 14,248
  • 33
  • 123
  • 181

1 Answers1

0

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);
Cepr0
  • 28,144
  • 8
  • 75
  • 101
  • Sorry not sure what you mean? Does it work in this case only because Child does not reference to Parent? – erotsppa Apr 24 '20 at 22:51
  • @erotsppa Practically. Bidirectional one-to-many is different from the unidirectional one that associated entity doesn't have a reference to the first one. And a bidirectional OTM is a little harder to implement due to the necessity of synchronizing both ends of the association. You can read more about it [here](https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-many). And [here](https://stackoverflow.com/a/30474303) you can find a recommendation of the SDR author Oliver Drotbohm about not using the Bidirectional OTM... – Cepr0 Apr 26 '20 at 13:02