Can I use DTO in repository?

Can I use DTO in repository?

That being said it is fine to pass back a DTO (or Application Object) from the Repository. The EF entities or Request/Resonse object are only needed for your persistent layer.

What should repository return?

Your repositories should return domain objects and the client of the repository can decide if it needs to do the mapping. By mapping the domain objects to view models (or something else) inside a repository, you prevent the client of your repositories from getting access to the underlying domain object.

Where should DTO be used?

A DTO is helpful whenever you need to group values in ad hoc structures for passing data around. From a pure design perspective, DTOs are a solution really close to perfection. DTOs help to further decouple presentation from the service layer and the domain model.

What is DTO model?

With MVC data transfer objects are often used to map domain models to simpler objects that will ultimately get displayed by the view. From Wikipedia: Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems.

What should a repository do?

The REPOSITORY retrieves the requested object, encapsulating the machinery of database queries and metadata mapping. REPOSITORIES can implement a variety of queries that select objects based on whatever criteria the client requires.

Is JPARepository a DAO?

It is about the DAO. In spring boot, there is JPARepository interface. This interface has been declare the methods such as save(), findById() .

Do you have to return DTO to repository?

But for that to work, the repository has to return an instance of that DTO. Otherwise, you would first have to map the data layer object that the repository returns to a DTO in the service layer and return that. That just seems wasteful.

How to create a repository using DTOs and mappers?

On save (), check if the entity already exists and then perform the create or update. With respect to doing the “create if not exists, else update”, that’s the type of complex data access logic that we don’t want any other constructs in our domain to have to know about: only the repos should care about that.

How does a DTO work in a service?

More often than not, services do little more than access a repository and return whatever the repository returns. But for that to work, the repository has to return an instance of that DTO. Otherwise, you would first have to map the data layer object that the repository returns to a DTO in the service layer and return that.

How are DTOs created in the service layer?

On top of that, if creation of the DTOs happens in the service layer, something that might have been done before in one repository call and thus one database query, now has to happen with multiple repository calls in the service layer to ‘compose’ the final DTO.