简体   繁体   中英

Spring Rest API validation should be in DTO or in entity?

In which tier should the validation be in a Spring Boot Rest API. I have some models, endpoints and DTOs. I added some @NotNull and @Size annotations in the DTO. I added the @Valid annotation in the endpoint along with the @RequestParam annotation.

But now I'm wondering if I should put validation in the @Entity classes as well? I feel like it would be a duplication of code. But I read that a tier should never rely on another one.

It's ironic how many people truly believe that validation should be something we partake upon in our controllers or the value objects which they exchange with business code and at no other place should there be concern for state validation.

We should always strive to perform validation at multiple stages of any application.

Consider for the moment a controller that accepts a value object that you intend to use to change a business entity in some service and that value object contains only a subset of fields that you intend to manipulate in a larger entity. You validate the value object in your presentation tier and pass that to your service which fetches the entity, takes the values from the value object and sets them on the appropriate entity. Perhaps that service method manipulates other fields too.

What guarantee do we have that the state of that entity is valid ?

While we validated the value object was valid, we only validated those inputs within the context of the subset of fields which were supplied. We didn't validate that those values in conjunction with the other existing state of the entity were still valid.

It's also important to try and guard against developer mistakes too. Test cases only get you so far and we all can agree we don't validate the validity of every combination of values in our tests. We often target very specific cases and scenarios and draw conclusions from there.

By applying validation not only to our presentation value objects but to our entities, you not only allow your test cases to focus on broad feature validation but you guarantee that your data store state is never compromised by the application.

在实体中,您应该添加需要数据处于健康状态的constraints ,并且所有validation逻辑都应该在DTO因为您的RestController服务于DTOscontroller负责在映射到实体之前检查验证。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM