views:

609

answers:

3

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?

+1  A: 

in a project of mine I used the service layer:

class ProductService {

    void removeById(long id);

}
dfa
A: 

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).

Nick Holt
+1  A: 

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();
}
bpapa