MVC Design – Should DAO Be Called from Controller or Model?

daodesign-patternsjavamvc

I have seen various arguments against the DAO being called from the Controller class directly and also the DAO from the Model class.Infact I personally feel that if we are following the MVC pattern , the controller should not coupled with the DAO , but the Model class should invoke the DAO from within and controller should invoke the model class.Why because , we can decouple the model class apart from a webapplication and expose the functionalities for various ways like for a REST service to use our model class.

If we write the DAO invocation in the controller , it would not be possible for a REST service to reuse the functionality right ? I have summarized both the approaches below.

Approach #1

  public class CustomerController extends HttpServlet {

    proctected void doPost(....)  {

            Customer customer = new Customer("xxxxx","23",1);
            new CustomerDAO().save(customer);

    }


 }

Approach #2

  public class CustomerController extends HttpServlet {

    proctected void doPost(....)  {

            Customer customer = new Customer("xxxxx","23",1);
            customer.save(customer);

    }


 }

 public class Customer {

   ...........

   private void save(Customer customer){

        new CustomerDAO().save(customer);

   }

}

Note

Here is what a definition of Model is :

Model:
The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.

I would need an expert opinion on this because I find many using #1 or #2 , So which one is it ?

Best Answer

In my opinion, you have to distinguish between the MVC pattern and the 3-tier architecture. To sum up:

3-tier architecture:

  • data: persisted data;
  • service: logical part of the application;
  • presentation: hmi, webservice...

The MVC pattern takes place in the presentation tier of the above architecture (for a webapp):

  • data: ...;
  • service: ...;
  • presentation:
    • controller: intercepts the HTTP request and returns the HTTP response;
    • model: stores data to be displayed/treated;
    • view: organises output/display.

Life cycle of a typical HTTP request:

  1. The user sends the HTTP request;
  2. The controller intercepts it;
  3. The controller calls the appropriate service;
  4. The service calls the appropriate dao, which returns some persisted data (for example);
  5. The service treats the data, and returns data to the controller;
  6. The controller stores the data in the appropriate model and calls the appropriate view;
  7. The view get instantiated with the model's data, and get returned as the HTTP response.
Related Topic