【问题标题】:How to add elements in a many-to-many relationship via Spring's @RepositoryRestResource REST API?如何通过 Spring 的 @RepositoryRestResource REST API 在多对多关系中添加元素?
【发布时间】:2014-12-03 06:22:05
【问题描述】:

我很难弄清楚如何使用@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 之类的东西,但到目前为止我还没有找到有效的结构。

【问题讨论】:

    标签: java spring spring-data-rest


    【解决方案1】:

    我在这里找到了答案:How to update reference object in Spring-data rest?

    通过使用“Content-Type: text/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

    【讨论】:

    • 感谢您提供答案和文档的链接。看到一个具体的例子后,文档的那部分就更有意义了。
    【解决方案2】:

    我一直讨厌 text/uri-list 内容类型,所以我做了一些研究,结果发现还有一种未记录的 JSON 格式可以使用:

    {
      "_links":{
        "rel":"/555",
        "rel":"/556"
      }
    }
    

    链接的 rel 可以是空字符串以外的任何内容,它们都可以相同。链接部分可以是被引用对象的自链接形式的整个 URL,但 URL 的最后一部分就足够了。 (forseslash +id)

    【讨论】:

    • 这也适用于 2.2.0 M4。 ``` { "_links":{ "1":{"href": "/555"}, "1":{"href": "/556"} } } ``
    猜你喜欢
    • 1970-01-01
    • 2012-04-24
    • 2019-01-02
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2013-05-05
    相关资源
    最近更新 更多