I am building an API Rest with Spring Boot and I would like to clarify a concept about my architecture, to see if the community can help me.
Imagine that in my database I have a table called Person
. I am mounting an architecture based on three layer architecture. The general scheme would be as follows:
On the one hand I have the
PersonDao.java
, which will be in charge of accessing the database to retrieve the tuples from thePerson
table. To do this, it uses a class calledPersonEntity.java
, which contains (as attributes) all the columns of the table.PersonDao.java
is going to return an object from thePersonModel.java
class.PersonModel.java
is the class that represents thePerson
business model.On the other hand, I have the
PersonService.java
, which is responsible for carrying out the business logic of my application. This service callsPersonaDao.java
to access the information stored in the database.PersonService.java
works with objects of thePersonModel.java
class, since this class represents the business objects of my application.PersonService.java
will always return aPersonDto,java
.Finally,
PersonController.java
. This controller will be the one that exposes the connection interface of the Rest API. He always works with DTO and communicates withPersonService.java
through DTO as well.
PersonController <-> (PersonDto) <-> PersonService <-> (PersonModel) <-> PersonDao <-> (PersonEntity) <-> DB
The question is: Is it necessary to use the PersonModel.java
class so that PersonService.java
only works with objects of this class? Or would it be better for PersonService.java
to work directly with objects from class PersonEntity.java
? If I do it this way it is to maintain the principle of single responsibility, so that each layer only works with objects of its scope.
If the answer is that PersonModel.java
is necessary to maintain the principle of single responsibility of each layer. Would something change if JpaRepository
were used? If I ask this question it is because in many tutorials and examples I see that when JpaRepository
is used, the services work directly with the entities. In this case, shouldn't we create a class that represents the business object for the services?
EDIT: In the answer to this question (https://stackoverflow.com/questions/34084203), the architecture that makes sense in my head would be reflected, but surely it is not the most correct thing. The conclusion I come to is that each layer would use its own kind of objects. Copy / paste of the answer:
Typically you have different layers:
- A persistence layer to store data
- Business layer to operate on data
- A presentation layer to expose data
Typically, each layer would use its own kind of objects:
- Persistence Layer: Repositories, Entities
- Business Layer: Services, Domain Objects
- Presentation Layer: Controllers, DTOs
This means each layer would only work with its own objects and never ever pass them to another layer.
Thanks in advance.