I have a REST service producing JSON and consuming JSON.
A lot of this are simple CRUD operations. My initial idea was to simply use the DAOs directly in the controller:
@ResponseBody()
@RequestMapping(value="/cars/{carID}", method = RequestMethod.PUT)
public Car saveCar(@PathVariable Long carId, @RequestBody Car car) {
carDAO.save(car);
return car
}
In this example, Car
is a persistent @Entity
and the save
method is just a wrapper for EntityManger.persist();
I heard that it is generally a bad idea to use persistence classes in the controllers for your API. Is that true? If so, why and what is the alternative?
Is this a good idea? Do I need a service layer? If not when would I need it?
Assume the application grows and the operations get even more complex, would I then need a service layer?
Whenever you define a non-CRUD operation you will be in trouble to find a HTTP method, which describes the same thing. This can be solved by defining a new resource. So REST resources cannot be mapped 1:1 to entities. That’s the problem in your case.
Imho you need a domain model which is working with the entities and you need a delivery method, which transforms the HTTP request into commands or queries addressed to your domain model. I would check domain driven design if I were you, maybe you learn something you can use in your project.