我想扩展示例 Accessing JPA Data with REST通过将地址列表添加到 Person
实体。所以,我添加了一个带有 @OneToMany
注释的 addresses
列表:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Address> addresses = new ArrayList<>();
// get and set methods...
}
Address
类非常简单:
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String street;
private String number;
// get and set methods...
}
最后我添加了 AddressRepository
接口(interface):
public interface AddressRepository extends PagingAndSortingRepository<Address, Long> {}
然后我尝试用一些地址发布一个人:
curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Frodo", "lastName" : "Baggins", "addresses": [{"street": "somewhere", "number": 1},{"street": "anywhere", "number": 0}]}' http://localhost:8080/people
我得到的错误是:
Could not read document: Failed to convert from type [java.net.URI] to type [ws.model.Address] for value 'street';
nested exception is java.lang.IllegalArgumentException: Cannot resolve URI street. Is it local or remote? Only local URIs are resolvable. (through reference chain: ws.model.Person[\"addresses\"]->java.util.ArrayList[1]);
nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.net.URI] to type [ws.model.Address] for value 'street'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI street. Is it local or remote? Only local URIs are resolvable. (through reference chain: ws.model.Person[\"addresses\"]->java.util.ArrayList[1])
创建一对多和多对多关系并向它们发送 json 对象的正确方法是什么?
最佳答案
您应该先 POST 这两个地址,然后在您的个人 POST 中使用返回的 URL(例如 http://localhost:8080/addresses/1 和 http://localhost:8080/addresses/2):
curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Frodo", "lastName" : "Baggins", "addresses": ["http://localhost:8080/addresses/1","http://localhost:8080/addresses/2"]}' http://localhost:8080/people
如果你想先保存这个人然后添加它的地址你可以这样做:
curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Frodo", "lastName" : "Baggins"}' http://localhost:8080/people
curl -i -X POST -H "Content-Type:application/json" -d '{"street": "somewhere", "number": 1}' http://localhost:8080/addresses
curl -i -X POST -H "Content-Type:application/json" -d '{"street": "anywhere", "number": 0}' http://localhost:8080/addresses
curl -i -X PATCH -H "Content-Type: text/uri-list" -d "http://localhost:8080/addresses/1
http://localhost:8080/addresses/2" http://localhost:8080/people/1/addresses
关于java - Spring JPA REST 一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34583515/