r/SpringBoot • • Jan 04 '26

Question DTO & Entity

I have created one api endpoint for the user registration, and while I made it I found few points like in which layer sanitization should be done (client -> controller -> service -> repository -> database) then I came to know about DTO. on We can use DTO object for parsing the user request data and apply sanitization and proper checks and then we can use response DTO as well to send back the response to the client.

Well I am learning springboot, and different tutorials are doing different things, so I want to know from you guys. What should be the proper structure here and using DTO layer is really still being used in today industry ?

43 Upvotes

23 comments sorted by

View all comments

Show parent comment

0

u/asarco Jan 04 '26 edited Jan 04 '26

I'm always over the fence with this, because so many people think "exposing" an entity to the FE as a mortal sin, but in so many cases it make things much simpler just return the entity.

The usual reason (apart from the sensitive information), is that "entity objects don't belong to the presentation layer". So then we simply create another exact duplicate class, and we spend CPU time copying the data from one object to the other. Conceptually might look nice, but to me it seems a waste of resources, and adds (a bit of) unnecessary complexity to a system.

And by using Jackson's @JsonView and other annotations, it is possible to customize the entity as much as needed, to protect sensitive data or for presenting it and reusing it in a different way.
I've only seen this done in a single project in my whole career, and it was actually a legacy project that used something similar to @JsonView, but they were custom annotations made by the original developers (not sure if it was before they existed in Jackson).

1

u/Ali_Ben_Amor999 Jan 04 '26

If you are worried about CPU waste, you should consider dropping JPA in the first place because the jpa provider is doing too much which make copying 5 or 20 fields negligible. While personally I don't see issue returning the entity with some Jackson view annotations if the entity is simple. But this can be prone to transactional context issues like transactional life cycles which require an open session even at controller level also it can make project inconsistent when you have an endpoint returning a POJO and another returning an entity but it all depends on the use case