5

I got some REST endpoint in Spring-RS which use an entity id as path variable. Most of the time, the first thing the method is doing is retrieving the entity using the id. Is there a way to automatically map the id to the entity, having only the entity as methods parameters ?

Current situation :

@RequestMapping(path="/{entityId})
public void method(@PathVariable String entityId) {
    Entity entity = entityRepository.findOne(entityId);
    //Do some work
}

What I would like to have :

@RequestMapping(path="/{entityId})
public void method(@PathVariable Entity entityId) {
    //Do some work
}
Teocali
  • 2,725
  • 2
  • 23
  • 39
  • `@RequestMapping(path="/{entityId}) public void method(@PathVariable String entityId) { Entity e = new Entity(entityId); }` You can't map a PathVar to an entity, BUT you can put part or all of you entity into the payload of you rest request. – Zorglube Dec 20 '16 at 10:28

2 Answers2

1

That's possible if you are using Spring Data. See official documentation

Javasick
  • 2,753
  • 1
  • 23
  • 35
-1

You can do something like this:

@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) {

}

to get your custom object and Spring will try to convert the parameter to the given type.

I prefer to pass the id most of the times for security reasons.

ddarellis
  • 3,912
  • 3
  • 25
  • 53
  • 1
    The problem here is that I want the entity created by a request to database, not only from the data provided by the client – Teocali Dec 20 '16 at 12:53