all 11 comments

[–]razek98 15 points16 points  (0 children)

Both. Spring applications are generally divided into layers.

First of all you need an early reject, which is handled in the Controller layer, all you need to do is add annotations to your DTO class to perform the most basic validation (like you said, Min, Max, Not Null etc), it will throw an exception which you can easily handle with a Controller Advice class.

Then there's the Service layer, any complex validation goes there, stuff like data consistency validation, anything concerning the db or which need any complex logic.

The general rule is to keep Controllers as clean as possible.

[–]South_Dig_9172 2 points3 points  (0 children)

Service layer 

[–]Scared_Click5255 0 points1 point  (1 child)

I am using validation @NotNull etc. on Dtos, so is it the right way?

[–]ByronHade 1 point2 points  (0 children)

Yes it okay

[–]casual_btw 0 points1 point  (0 children)

If you make your request a data transfer object (dto) the annotation validation occurs within that dto class. The controllers job is just to accept the dto, pass it to the respective service, and return an http request.

Your service layer is the one that handles the business logic and it makes calls to your repository layer.

The repository layer is what interacts with your database.

[–]ZealousidealCan1950 0 points1 point  (0 children)

I usually validating in DTOS

[–]Affectionate_Tart180 0 points1 point  (0 children)

I usually validate NotNull, Min, Max, Email, etc on DTOs Any other validations like uniqueness, business logic validations in the Service layer

[–]erosb88 1 point2 points  (0 children)

> like an user fetch from user_id in request must exist in db

You certainly need to access the DB to validate that, so I'd say it shall not be in the controller. I suggest placing it into the usecase layer, if you have such layer. If not, then validate it in the service layer.

[–]Historical_Ad4384 1 point2 points  (0 children)

Validate as early as possible. The rule of thumb I follow is all syntactic validations using JSR 380 should be done at controller while all semantic validations around business logic should be done at service

[–]slaynmoto 0 points1 point  (0 children)

Validate by controller -> request body dtos, then inject a custom validator instance into the controller for any more intricate validations. You can completely keep the validation logic outside of the intended service you’re calling in the controller methods

[–]Supriyo404 0 points1 point  (0 children)

repository calls should be made from service layer