gpt4 book ai didi

java - 如何通过 Spring 的 @RepositoryRestResource REST API 在多对多关系中添加元素?

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:06 25 4
gpt4 key购买 nike

我无法弄清楚如何使用 @RepositoryRestResource 接口(interface)在两个相当简单的实体之间创建多对多关系。

例如,我有一个简单的父子实体关系是这样的:

@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;
}

我的存储库正在使用 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,但我似乎无法弄清楚如何使用内置接口(interface) PUT/PATCH 两者之间的关系。

似乎我应该能够使用 PUT 将 JSON 发送到类似 http://localhost:8080/api/parents/1/children 的地方,但到目前为止我还没有找到一个有效的结构。

最佳答案

我在这里找到了答案: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 .

关于java - 如何通过 Spring 的 @RepositoryRestResource REST API 在多对多关系中添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26259474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com