我想通过向实体添加地址列表来扩展使用REST访问JPA数据的示例Person
.所以,我添加了一个addresses
带@OneToMany
注释的列表:
@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 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
界面:
public interface AddressRepository extends PagingAndSortingRepository {}
然后我试着用一些地址发帖:
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对象发布到它们的正确方法?
您应首先发布两个地址,然后在Person 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