我应该在哪里创建新实体 - 是否在表示层?
当我刚刚学习 Java 的所有成果和一切时,我想找出在我脑海中盘旋了一段时间的一件事。 下面的代码是两个不同类中两种方法的快速示例。第一个显然是某个页面的控制器,另一个是服务的一部分。
@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);
}
所以我的问题是,新实体 SomeEntity
的创建及其属性的设置是否应该在表示层部分中完成,如上所示,还是应该在 saveSomeEntity
中以某种方式完成方法通过将所有参数传递给它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控制器不是表示层。它是 MVC 中的 C。持久层应该只关心持久性,而不是模型对象的创建。上面的代码就OK了。有些人会在服务中创建对象,而不是在控制器中,但参数在控制器中很容易获得,因此恕我直言,这是可以接受的。
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.
是的,可以在任何层创建实体。
有些人更喜欢 DTO(具有相同结构的单独对象),然后将其转换为实体。
只是避免在 jsps 中编写 java 代码。实例化控制器中的对象,或将其留给某种绑定机制。
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.