【发布时间】:2016-04-07 14:45:34
【问题描述】:
我想通过将地址列表添加到Person 实体来扩展示例Accessing JPA Data with REST。所以,我添加了一个列表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<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接口:
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对象发布到它们的正确方法是什么?
【问题讨论】:
-
您已经向我们展示了您的 ORM 的实体类,但您没有向我们展示任何为 REST 注释的内容。
-
查看此答案,建议使用自定义转换器stackoverflow.com/questions/24781516/…
-
@scottb 我在教程中使用
@RepositoryRestResource注释,用于两个存储库(人员、地址)。这将为实体创建公共 REST 端点。 -
我相信它与
spring-data和spring-data-jpa而不是普通的spring 和jpa 更相关。重新标记
标签: java rest spring-data-jpa spring-data-rest