0

As I'm just learning all the fruits of Java and everything I wanted to find out one thing which was flying around in my mind for some time. The code bellow is quick example of two methods in two different classes. First one is obviously a controller for some page and the other one is part of service.

@RequestMapping("/something)
public void doSomething() {
    ...

    SomeEntity example = new SomeEntity();
    example.setAccount(account);
    example.setSmthElse(else);
    example.setDate(new Date());
    example.setSomething(something);

    someService.saveSomeEntity(example);
}

... 

public void saveSomeEntity(SomeEntity object) {
    someEntityDAO.save(object);
}

So my question here is should the creation of the new entity SomeEntity and setting of it's properties be done in the presentation layer part as above or should it be done somehow in the saveSomeEntity method by passing all the params to it?

Rihards
  • 10,241
  • 14
  • 58
  • 78

2 Answers2

3

The controller is not the presentation layer. Its the C in MVC. The persistence layer should only be concerned with persistence, not Model object creation. The code above is OK. Some would create the objects in the service, not in the controller, but the params are readily available in the controller so IMHO its acceptable.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • Sorry my mistake calling the controller a presentation layer. I'm bit struggling with the layer stuff yet to figure out which is which. (English is not my first language) – Rihards Jun 17 '11 at 14:49
2

Yes, the entity can be created at any layer.

Some people prefer DTOs (separate objects with the same structure) which are then translated to the entities.

Just avoid writing java code in the jsps. Instantiate the objects in the controller, or leave that to some binding mechanism.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • you would really create entities in a jsp? – hvgotcodes Jun 17 '11 at 14:26
  • not in the jsp of course, but in the web layer (controllers) - yes. And actually - between the jsp and controllers - some binding mechanism. – Bozho Jun 17 '11 at 14:27
  • I think he is referring to a set of objects in the Controller layer that mirror the domain layer. You would than map the object returned from the domain layer to the controller objects. Seems redundant, but if the domain layer is actually behind a service than depending on the circumstances, may not be. – Casey Jun 17 '11 at 14:28
  • @bozho, wouldn't it be more accurate to say in the controller or service layers, as opposed to any layer? – hvgotcodes Jun 17 '11 at 14:31
  • it can be any layer, even the UI layer if it is not JSP (if it is gwt or vaadin for example) – Bozho Jun 17 '11 at 14:46
  • right, but in that case, the entity is created again at the server after it is sent over the wire? although i guess that depends on the tech used... – hvgotcodes Jun 17 '11 at 14:57