【发布时间】:2018-05-01 14:57:03
【问题描述】:
在我的项目中,我有两个域模型。一个父实体和一个子实体。父级引用子实体的列表。 (例如帖子和评论)两个实体都有它们的弹簧数据 JPA CrudRepository<Long, ModelClass> 接口,它们公开为 @RepositoryRestResource
HTTP GET 和 PUT 操作工作正常,并返回这些模型的漂亮 HATEOS 表示。
现在我需要一个特殊的 REST 端点“创建一个引用一个或多个已经存在子实体的新父级”。我想将对孩子的引用发布为我在请求正文中传递的文本/uri-list,如下所示:
POST http://localhost:8080/api/v1/createNewParent
HEADER
Content-Type: text/uri-list
HTTP REQUEST BODY:
http://localhost:8080/api/v1/Child/4711
http://localhost:8080/api/v1/Child/4712
http://localhost:8080/api/v1/Child/4713
如何实现这个休息端点?这是我迄今为止尝试过的:
@Autowired
ParentRepo parentRepo // Spring Data JPA repository for "parent" entity
@RequestMapping(value = "/createNewParent", method = RequestMethod.POST)
public @ResponseBody String createNewParentWithChildren(
@RequestBody Resources<ChildModel> childList,
PersistentEntityResourceAssembler resourceAssembler
)
{
Collection<ChildModel> childrenObjects = childList.getContent()
// Ok, this gives me the URIs I've posted
List<Link> links = proposalResource.getLinks();
// But now how to convert these URIs to domain objects???
List<ChildModel> listOfChildren = ... ???? ...
ParentModel newParnet = new ParentModel(listOfChildren)
parentRepo.save(newParent)
}
参考/相关 https://github.com/spring-projects/spring-hateoas/issues/292
【问题讨论】:
-
备注:我知道如何通过 RepositoryRestResource 公开的 spring-hateoas 休息端点将元素添加到子列表中。在那里,我可以通过 POSTing text/uri-list 创建parnet 子关系,如下所述:stackoverflow.com/questions/26259474/… 但我想知道我是如何在我自己的自定义休息端点中做到这一点的。
-
有很多类似的问题。但我的特殊情况是:我想创建一个 NEW 父实体,它将链接到已经 EXISTING 子实体。
-
我有点困惑,但是孩子怎么能在父母之前存在呢?就像您对尚不存在的帖子创建评论一样。通常你也会尽量避免在资源端点中使用动词,因为它会给端点带来某种 RPC 气味,但对于 REST,它是否存在并不重要。
-
@RomanVottner 有两种 OneToMany 关系:组合和聚合。 (参见stackoverflow.com/questions/885937/…)在我的领域模型中,两个实体都可以独立存在并拥有自己的生命周期。它们可以链接。
-
也许“论坛帖子”和“评论”是一个不好的例子。一个更好的例子是“学校”和“学生”。一所学校有几个学生。 (学校 -> OneToMany ---> 学生)但是一个学生可能会搬到另一所学校,例如当学校关闭或他搬到他住的地方时。学生独自存在。而我的问题是:我想建立一所新学校。我希望它与一些已经存在的学生有关。
标签: java spring spring-data-rest spring-hateoas