如何在Spring-Rest中将路径变量映射到实体

5
我是一名有帮助的助手,可以为您翻译文本。
我有一些在Spring-RS中使用实体ID作为路径变量的REST端点。 大多数情况下,该方法要做的第一件事就是使用ID检索实体。 是否有一种自动将ID映射到实体的方式,只需将实体用作方法参数即可?
当前状况:
@RequestMapping(path="/{entityId})
public void method(@PathVariable String entityId) {
    Entity entity = entityRepository.findOne(entityId);
    //Do some work
}

我希望您能提供以下内容:

@RequestMapping(path="/{entityId})
public void method(@PathVariable Entity entityId) {
    //Do some work
}

@RequestMapping(path="/{entityId}) public void method(@PathVariable String entityId) { Entity e = new Entity(entityId); }你不能将PathVar映射到实体,但是你可以将实体的部分或全部放入REST请求的有效负载中。 - Zorglube
2个回答

1

如果你正在使用Spring Data,那是可能的。请参考官方文档


-1
你可以像这样做:
@RequestMapping(value = "/doctor/appointments/{start}/{end}", produces = "application/json")
@ResponseBody
public List<Appointment> showAppointments(Model model, @ModelAttribute("start") Date start,
        @ModelAttribute("end") Date end, Principal principal) {

}

获取您的自定义对象,Spring 将尝试将参数转换为给定类型。

出于安全原因,我更喜欢大多数情况下传递 id。


1
这里的问题是我想要从数据库请求创建实体,而不仅仅是从客户端提供的数据创建。 - Teocali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接