Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Domain Object handling Best Practice

Lets assume a simple Spring MVC Controller that receives the ID of a domain object. The Controller should call a service that should do something with that domain object.

Where do you "convert" the ID of the domain object into the domain object by loading it from the database? This should not be done by the Controller. So the service method interface has to use accept the ID of the domain object instead of the domain object itself. But the interface of the service would be nicer if it takes the domain object as a parameter.

What are your thoughts about this common use case? How do you solve this?

like image 771
Thomas Einwaller Avatar asked Jul 03 '09 14:07

Thomas Einwaller


3 Answers

The controller should pass the id down into the service layer and then get back whatever is needed to render the rest of the HTTP response.

So -

Map<String,Object> doGet (@RequestParam("id") int id) {
     return serviceLayer.getStuffByDomainObjectId(id);
}

Anything else is just going to be polluting the web layer, which shouldn't care at all about persistence. The entire purpose of the service layer is to get domain objects and tell them to perform their business logic. So, a database call should reside in the service layer as such -

public Map<String,Object> getStuffByDomainObjectId(int id) {
    DomainObject domainObject = dao.getDomainObjectById(id);
    domainObject.businessLogicMethod();
    return domainObject.map();
}
like image 198
bpapa Avatar answered Oct 20 '22 21:10

bpapa


in a project of mine I used the service layer:

class ProductService {

    void removeById(long id);

}
like image 41
dfa Avatar answered Oct 20 '22 20:10

dfa


I think this would depend on whether the service is remote or local. As a rule I try to pass IDs where possible to remote services but prefer objects for local ones.

The reasoning behind this is that it reduces network traffic by only sending what is absolutely necessary to remote services and prevents multiple calls to DAOs for local services (although with Hibernate caching this might be a mute point for local services).

like image 42
Nick Holt Avatar answered Oct 20 '22 21:10

Nick Holt