简体   繁体   English

Spring MVC域对象处理最佳实践

[英]Spring MVC Domain Object handling Best Practice

Lets assume a simple Spring MVC Controller that receives the ID of a domain object. 让我们假设一个简单的Spring MVC Controller接收域对象的ID。 The Controller should call a service that should do something with that domain object. Controller应该调用应该对该域对象执行某些操作的服务。

Where do you "convert" the ID of the domain object into the domain object by loading it from the database? 通过从数据库加载域对象的ID,将域名对象的ID“转换”到哪里? 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. 因此服务方法接口必须使用接受域对象ID而不是域对象本身。 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? 你是如何解决这个问题的?

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. 控制器应该将id传递到服务层,然后返回呈现其余HTTP响应所需的任何内容。

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

in a project of mine I used the service layer: 在我的一个项目中,我使用了服务层:

class ProductService {

    void removeById(long id);

}

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. 作为一项规则,我尝试尽可能将ID传递给远程服务,但更喜欢本地对象。

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). 这背后的原因是它通过仅向远程服务发送绝对必要的内容来减少网络流量,并防止对本地服务的DAO多次调用(尽管使用Hibernate缓存,这可能是本地服务的静音点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM