javajpadto

DTO and how this works exactly?


1. With DTO is response faster

Why ? When you make a endpoint without DTO for example @GetMapping("/{id}") which give you that exact "Employee" which have 20columns,but Domain need just 3columns, Frontend guy can from Json get that data by response.Name or response.LastName. What is exactly here faster which DTO ? Because that data is pulled from database anyway and with same speed with DTO or without no ?


Solution

  • First of all, DTO stands for data transfer object. It should consist of only primitive parts or other DTOs. And in particular shouldn't have any behaviour to it.

    1. With DTO is response faster

    Fetching and sending less data over the wire takes less time.

    1. Edit response without DTO, can change data in the Database

    When using Hibernate, every returned entity is bound to the persistence context while the transaction is running, and the entity is not detached, every mutation of the entity is written back to the persisted entity without the need to invoke

    repository.save(entity)
    
    1. DTO is better with multiple requests

    By itself, this statement is debatable.

    You could create a DTO for id 5 and keep it, for let's say 60 seconds, and when a successive call for the same id arrives the controller returns the cached DTO instead of doing a roundtrip to the db and creating an identical DTO.

    Depending on the architecture and load different approaches could be considered. For example 1st- or 2nd-level caches or views.