In which layer do I access the database in the MVC project
I have a question about accessing a database in an mvc application. Where should the database access logic be located?
should i be placed in every model? (if I have a Person model)
Person p = new Person();
p.save();
if it is put into every controller? or should I create another set of classes just to execute the database logic, which means I have an extra layer in addition to the model, view and controller?
How it's done? Also if using ORM?
source to share
In MVC pattern, M stands for Models, View V stands for, C stands for Controller. The general flow of MVC is that once a request comes in, the controller receives it and does the necessary processing, retrieves the results data, and then passes the results data to view for rendering. Once the display layer is rendered, it is displayed to users through a graphical interface.
The controller can be thought of as the commander, it is in control of the process, but it is not good to handle retrieving data in the controller. The model should be responsible for receiving and organizing the data. This means that data objects should be stored in Model instead of Controller, Controller calls Model to retrieve data objects.
In your case, my suggestion is as follows:
-
PersonController
, it calls a methodPersonService.savePerson(Person person)
to save the data (or else it retrieves the result). I suggest that the controller layer be thin. -
PersonService
, it has a methodsavePerson(Person person)
, this method calls a methodPersonDAO.savePerson(Person person)
to save / retrieve project data (here it stores data) and possibly other processing. This is where the business logic comes in. -
PersonDAO
, it has several methods that deal with objectsPerson
(for examplesavePerson(Person person)
,getAllPersons()
), processes the database in this layer. But these methods must be independent from the business logic (since the business logic must be wrapped inPersonService
). -
Person
object, value object , it just defines what attributes should havePerson
, for examplename
,age
etc., with methodsget/set
that are used to pass data across different levels. He doesn't deal with the database at all.
Whereas for a non-complex application, the service level is not really needed and can be integrated into the controller level, which means that it is only PersonController
okay.
source to share
Others have pointed out that database access is a controller function, but I recommend that you create a new library project to handle database interactions. Typically this name will be named "customerService.jar", which means it encapsulates whatever you want to do to the customer. This will simplify your application and greatly increase the reusability of your code.
This would be the approach:
- Define an interface that exposes business layer operations (for example, changeUserRole (long userId, Role newRole) or makePayment (long accountId, BigDecimal amount) , not the CRUD approach updateUser (User User) , etc. Usually some of the methods displayed interface, will look like CRUD methods, but can do more at the end of the database (for example, check account status, maintain audit tables).
- Implement your business logic in this layer. Purists will say that there should be a separate layer for business logic, but that makes it difficult to use SQL objects (in particular, connections) to efficiently access the database. In my experience, these two layers need to be combined to keep the system simple and efficient.
- Use an ORM tool to access the database and map from business objects to the database. (MyBatis is my favorite). If your database accurately reflects your business model, you probably won't need separate DAOs and business objects.
- Inject an instance of your customerService into your MVC web controller. The controller's job is now to validate user input, populate the model, submit requests to the CustomerService, and return response data to the model.
So, if your needs change in the future (for example, you need to create your own IOS or Android app), you have a reusable service that will happily do the job. Likewise, if architects insist on exposing it as a REST or SOAP service, you only need to add the "glue logic" to implement the REST or SOAP service.
Plus, you'll easily smear customer service in website tests.
Good luck!
source to share
It's always best to separate your code and group it according to their behavior. Model classes can be used as a logical representation of your database. You should have some Utility / helper classes that do your DB operations and the controller should interact with them.
Ideally, you should have as many model classes (if not more) as there are tables in the database.
When you use an ORM, joins and mappings (after being declared) go back to their original position and focus on the business logic.
source to share
In a web application that uses a framework like Spring or Jersey (which you should be using), it is generally best to keep your "controllers" (HTTP request handlers) as simple as practical, wrappers around the service layer that contains your business logic such as database access. This makes testing much easier as you can test the business logic directly without the complications of HTTP requests and make it easier to reuse your business logic in future changes such as adding scheduled tasks.
When more than simple CRUD operations are associated with something like a Person object, I will create PersonService
with methods that are expressed in terms of business operations and inject that service into the controller. For simple CRUD operations, I usually use Spring Data Stores directly from the controller.
source to share
Define a function that accesses Db or performs DB related operations in a class file, which we call a model, and then access that function using that class object in the controller. A controller is just a set of functions that give us the DB results and assign those results to variables in the controller and access those variables in the view, which is your interface
source to share