且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在spring mvc控制器中使用Services和DAO

更新时间:2023-02-13 08:13:37

DAO更细化并处理一个特定的实体。服务提供宏观层面的功能,最终可以使用多个DAO。通常,服务用于定义事务边界以获得原子性。换句话说,如果最终使用多个DAO更新多个表,则在服务中定义事务边界将有助于提交或回滚对DB完成的所有更改。



您的设计,因为您主要为各种实体做CRUD,似乎服务并没有增加价值。然而,将网络前端看作是更新数据的一种方式。服务的使用将允许您将与网络服务相同的功能再次暴露给其他形式的客户端,如第三方集成商等。



总之,您的设计似乎符合常规做法。如果您觉得可以将多个服务组合成一个基于某些常见主题的服务,以减少代码开销,那么您应该继续执行。最后,最终的目标是创建可维护的代码,当需要时,没有人会害怕改变。


I'm building a web application that primarily constitutes of CRUD operations of data from back end/database. There are instances where in I have to write business logic(I'm sure we will have more business logic built as we go deeper in to development). Currently for each UI screen I'm creating I create a model class,Service class, DAO class, a controller(it's servlet essentially) and bunch of jsp pages. In most cases the service class just calls the methods from DAO to pass in model objects. Essentially we use model classes to map data from UI screens. Hence the controller will have the model objects populated when a form is submitted. I have started using service classes to keep a separation layer from web layer to DAO layer. But at times I feel that the service class is just adding unnecessary level of API calls, I would think that I could just inject the DAO in to Controller and complete the task faster. I want to use the service class only when there is additional business logic to be performed. If you have to design an application what factors do you consider using controller->DAO vs controller->Service->DAO control flow?

DAOs are more granular and deal with one specific entity. Services provide macro level functionalities and can end up using more than one DAO. Typically, Services are used for defining transaction boundaries to gain atomicity. In other words, if you end up updating multiple tables using multiple DAOs, defining transaction boundary at service will help in either committing or rollbacking all the changes done to DB.

In your design, since you are primarily doing CRUD for various entities, it may seem that services are not adding much value. However, think of web-based front end as one way of updating data. Usage of services will allow you to expose same capabilities as a web-service later to other forms of client like third party integrators, etc.

So, in summary, your design seems to be in line with conventional practices. If you feel that you can combine multiple services into one based on some common theme such that it can reduce the overhead of code, then, you should go ahead and do it. At the end of day, ultimate goal is to create maintainable code which no one is afraid to change when need arises.