问题描述
我在弄清楚如何使用@RepositoryRestResource接口在两个相当简单的实体之间创建多对多关系时遇到了麻烦.
I'm having trouble figuring out exactly how to use the @RepositoryRestResource interface to create many-to-many relationships between two fairly simple entities.
例如,我有一个简单的父子实体关系,如下所示:
For example, I have a simple parent-child entity relationship like this:
@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:
My repositories are using the vanilla 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两者之间的关系.
I’ve been successful in using POST to create the individual ParentEntity and ChildEntity but I can’t seem to figure out how to PUT/PATCH the relationships between the two using the built-in interface.
似乎我应该能够使用PUT将JSON发送到类似http://localhost:8080/api/parents/1/children
之类的东西,但是到目前为止,我还没有找到一种有效的结构.
It seems like I should be able to use a PUT to send JSON to something like http://localhost:8080/api/parents/1/children
, but so far I'm not finding a structure that works.
推荐答案
我在这里找到了答案:
I found an answer here: How to update reference object in Spring-data rest?
通过使用"Content-Type:文本/uri-list"而不是JSON,可以通过PUT将资源添加"到集合中并传递URI.您可以使用DELETE删除资源.
By using "Content-Type: text/uri-list" instead of JSON, it is possible to "add" a resource to the collection with a PUT and pass in the URI. You can remove the resource with a DELETE.
经过一番挖掘,我发现Spring文档确实对此进行了描述: http://docs.spring.io/spring-data/rest/docs/2.2.0.RELEASE/reference/html/#repository-resources.association-资源.
After some digging, I discovered that the Spring documentation does describe this: http://docs.spring.io/spring-data/rest/docs/2.2.0.RELEASE/reference/html/#repository-resources.association-resource.
这篇关于如何通过Spring的@RepositoryRestResource REST API在多对多关系中添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!