我在弄清楚究竟如何使用@RepositoryRestResource接口来创建两个相当简单的实体之间的多对多关系时遇到了麻烦。
例如,我有一个简单的父子实体关系,如下所示:
@Entity public class ParentEntity { @Id @GeneratedValue private Long id; @ManyToMany private List<ChildEntity> children; } @Entity public class ChildEntity { @Id @GeneratedValue private Long id; @ManyToMany(mappedBy="children") private List<ParentEntity> parents; }
我的存储库正在使用普通的Spring @RepositoryRestResource HATEOS API:
@RepositoryRestResource(collectionResourceRel = "parents", path = "parents") public interface ParentRepository extends PagingAndSortingRepository<ParentEntity, Long> { } @RepositoryRestResource(collectionResourceRel = "children", path = "children") public interface ChildRepository extends PagingAndSortingRepository<ChildEntity, Long> { }
我已经成功地使用POST创建了单独的ParentEntity和ChildEntity,但似乎无法弄清楚如何使用内置接口来PUT / PATCH两者之间的关系。
看来我应该能够使用PUT将JSON发送到类似的东西http://localhost:8080/api/parents/1/children,但是到目前为止,我还没有找到一种有效的结构。
http://localhost:8080/api/parents/1/children
我在这里找到了答案:如何在Spring数据表中更新引用对象?
通过使用“ Content-Type:文本/ uri- list”而不是JSON,可以通过PUT将资源“添加”到集合中并传递URI。您可以使用DELETE删除资源。
经过一番挖掘,我发现Spring文档确实对此进行了描述:http : //docs.spring.io/spring- data/rest/docs/2.2.0.RELEASE/reference/html/#repository-resources.association- resource。