Annotations from javax.validation.constraints not working

后端 未结 15 1351
广开言路
广开言路 2020-11-28 06:23

What configuration is needed to use annotations from javax.validation.constraints like @Size, @NotNull, etc.? Here\'s my code:

15条回答
  •  春和景丽
    2020-11-28 06:26

    You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.

    An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.

    Your code should go like this:

    @PrePersist
    public void prePersist(SomeEntity someEntity){
        Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
        Set> = validator.validate(someEntity);
        //do stuff with them, like notify client what was the wrong field, log them, or, if empty, be happy
    }
    

提交回复
热议问题