简体   繁体   English

如何使用 spring 数据 r2dbc 验证实体?

[英]How can I validate entities with spring data r2dbc?

In Spring data JPA there are annotations that can be used to set up validations for entities in a declarative manner.在 Spring 数据 JPA 中,有注释可用于以声明方式为实体设置验证。 They can be found in javax.validation.constraints.* or additionally in org.hibernate.validator.constraints.* (in the case when Hibernate is plugged in).它们可以在javax.validation.constraints.*org.hibernate.validator.constraints.*中找到(在插入 Hibernate 的情况下)。

Example:例子:

    @NotNull
    private String lastName;

However, if the case of Spring data r2dbc they do not work out of the box.但是,如果是 Spring 数据 r2dbc,则开箱即用。

Is there any simple and smooth way to set up validations for entities in Spring data r2dbc? Spring 数据 r2dbc 中的实体是否有任何简单流畅的方法来设置验证? That should not be too difficult in my opinion because probably it does not require full ORM support, just a matter of callbacks for checking object fields before persisting it.在我看来,这不应该太困难,因为它可能不需要完整的 ORM 支持,只是在持久化之前检查 object 字段的回调问题。

  1. In the RestController, validate the incoming request body using the annotations from Bean validation and Hibernate validators.在 RestController 中,使用来自 Bean 验证和 Hibernate 验证器的注释来验证传入的请求正文。
  2. For RouterFunction or manal validation in your service, inject a Validator or ValidatorFactory to validate the request body before the data is (converted and) persisted into databases.对于服务中的 RouterFunction 或手动验证,在数据(转换和)持久化到数据库之前,注入 Validator 或 ValidatorFactory 以验证请求正文。
  3. JPA is tightly integrated with Bean Validation/Hibernate Validator, besides validation, it will affect the generated schemes by default. JPA 与 Bean Validation/Hibernate Validator 紧密集成,除了验证之外,它默认会影响生成的方案。
  4. In a real world application, do not use the data layered entity classes in the web layer as request body class.在现实世界的应用程序中,不要使用 web 层中的数据分层实体类作为请求主体类。

It works very fine with Bean Validation and Hibernate Validation.它与 Bean Validation 和 Hibernate Validation 一起工作得很好。

You can use all the same annotations you did in JPA, since you do it in your DTOs.您可以使用在 JPA 中所做的所有相同注释,因为您是在 DTO 中进行的。

See the example:看例子:

@Data
public class UserDto {

    private String name;

    @NotNull(message = "Last name can not be empty")
    private String lastName;

    @Min(value = 10, message = "Required min age is 10")
    @Max(value = 50, message = "Required max age is 50")
    private int age;
}

Then your controller would be annotated:然后你的 controller 将被注释:

@RestController
@RequestMapping("user")
public class RegistrationController {

    @Autowired
    private UserService userService;

    @PostMapping("register")
    public Mono<UserDto> register(@Valid @RequestBody Mono<UserDto> userDtoMono{
        return this.userService.registerUser(userDtoMono);
    }
}

The only thing now is that you have to personalize your message, so that it returns the one you have set in your DTO.现在唯一的事情是您必须个性化您的消息,以便它返回您在 DTO 中设置的消息。 To override it you should create an ExceptionHandler.要覆盖它,您应该创建一个 ExceptionHandler。

@ControllerAdvice
public class ValidationHandler {

    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity<List<String>> handleException(WebExchangeBindException e) {
        var errors = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return ResponseEntity.badRequest().body(errors);
    }

}

I've been using it in my projects and got this example from: https://www.vinsguru.com/spring-webflux-validation/我一直在我的项目中使用它,并从以下位置获得了这个示例: https://www.vinsguru.com/spring-webflux-validation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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