Implementing cross-validation in java

2019-09-06 18:26发布

I use Spring Roo + jpa + hibernate and I would like to implement cross-validation (validation of several fields at the same time) in my application.

I am not sure how to go about implementing it. Can anyone please advise me and/or direct me to relevant documentation?

1条回答
放荡不羁爱自由
2楼-- · 2019-09-06 19:13

Have a look at Hibernate Validator, which allows entity validation (using annotations).

http://www.hibernate.org/subprojects/validator.html

In short, you annotate your field constraints by placing hibernate validator/ JPA annotations above them. (E.g. @Min(10)) and use the following piece of code to find any invalid fields;

ValidatorFactory factory = Validation.byDefaultProvider().configure().traversableResolver(new CustomTraversableResolver() ).buildValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<BaseValidationObject>> constraintViolations = Validator.validate(myEntityToValidate);

If you need to validate specific relationships between entities, you can write custom validators to fit that need.

查看更多
登录 后发表回答