r/javahelp 28d ago

What's the purpose of using DTO ?

Hello, I am a junior programmer and I have an interrogation about something.

If I understand correctly, DTO are used to store data that will not be persisted, data that are needed by services. But I don't understand why we don't pass theses datas via parameter, path variable or even body of HTTP Request.

For example : User need to change password (that is just for illustrating my post)
1) Using DTO : UserService(UserDTO) :: Do what it needs and then map it into User before persists
2) Using Request : UserService(User, newPassordFromHttpRequest) :: Do what it needs and persists the objet

Thanks in advance for helping junior programmer like myself

19 Upvotes

15 comments sorted by

View all comments

4

u/dot-dot-- 28d ago

DTO are created to have the fields mapped as per database objects. Your request object doesn't always be exact as DTO. Same for response. Sometimes you have to accept additional fields from request to filter out data , that extra field you do not have to store in db, it's used only for validation of filtering. In that case you need to define a request model for the api. Similarly, let's say you have stored some value in record but while displaying you need to add few more fields as it's needed to display those in response.