Post an entity with Spring Data REST which has relations

后端 未结 1 1883
广开言路
广开言路 2020-12-31 16:41

I\'m using Spring Data Rest. I have a problem trying to POST an object with association(e.g. address is a field in my entity that is mapped as many to one).

The que

相关标签:
1条回答
  • 2020-12-31 17:11

    If you have a model like this:

    @Entity
    public class User {
        //..
        private String name;
    
        @OneToMany(mappedBy = "user")
        private Set<Address> addresses = new HashSet<>();
        //..
    }
    
    @Entity
    public class Address {
        //..
        @ManyToOne
        private User user;
        //..
    }
    

    then you can POST a new User with its addresses like this:

    POST http://localhost:8080/api/users
    {
        "name" : "user1",
        "addresses" : [
            "http://localhost:8080/api/addresses/1",
            "http://localhost:8080/api/addresses/2"
            ]
    }
    

    Before POST a new User, addresses ID#1 and ID#2 must be already persisted.

    0 讨论(0)
提交回复
热议问题