Java – in which layer do I access the database in the MVC design

I have a question about database access in MVC applications Where should I put my database access logic?

Should it be placed in each model? (if I have a model)

Person p = new Person();
p.save();

Should it be placed in each controller? Or should I create a different set of classes to execute database logic, which means I have an additional layer in addition to models, views and controllers?

How did this happen? What if ORM is used?

Solution

In MVC mode, M represents the model, V represents the view, and C represents the controller A common development of MVC applications is that once the request arrives, the controller will obtain it and perform necessary processing, retrieve the result data, and then pass the result data to the view for rendering After rendering the view layer, it is displayed to the user through the GUI

The controller can be regarded as a commander. It controls the process, but handling data retrieval in the controller is not good The model shall be responsible for retrieving and organizing data This means that the data object should be stored in the model instead of the controller, and the controller calls the model to retrieve the data object

In your case, my suggestion is that it requires the following components:

>Personcontroller, which calls personservice The saveperson (person person) method saves the data (or in other cases it retrieves the results) I suggest that the controller layer should be very thin. > Personservice has the method saveperson (person person), which calls persondao Save person (person person) method to save / retrieve project data (save data here), and perhaps other processing methods Business logic is here. > Person Dao, which has several methods to handle person objects (such as saveperson (person person), getallpersons ()), handles the database at this layer However, these methods should be independent of the business logic (because the business logic should be processed in personservice). > The person object is a value object. It just uses the get / set method to define the attributes that the person should have, such as name, age, etc., to transfer data through different layers It does not involve databases at all

For non complex applications, the service layer is not very necessary and can be integrated into the controller layer, which means that only the person controller is required

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>