How to map a path variable to an entity in spring-rest

3k views Asked by At

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
}
2

There are 2 answers

1
ddarellis On

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.

0
Javasick On

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