问题描述
我正在尝试使用此处指定的Java EE 6验证
I am trying to use Java EE 6 Validation as specified here
我注释了一个简单的字段
I have annotated a simple field
@Max(11)
@Min(3)
private int numAllowed;
文档说对于内置约束,默认实现可用但我该怎么做指定这个。我的约束检查没有开始。我希望它能够调用字段的setter方法。我班上唯一的进口是
The docs says "For a built-in constraint, a default implementation is available" but how do I specify this. My constraints checks are not kicking in. I would expect it to work on calling of the setter method for the field. The only import in my class is
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
我如何/在何处指定实施?
我把限制放在一个简单的POJO而不是@Entity类的字段上,这样可以吗?
How/where do I specify the implementation?I am putting the constraint on a filed in a simple POJO not an @Entity class, is this ok?
推荐答案
您对注释的使用很好。每个放心的人都有一个验证器实现。
Your use of the annotations is just fine. There's a validator implementation for each of those rest assured.
但是,在某些时候你需要触发这个POJO的验证。如果它是 @Entity
,那么你的JPA提供者会触发验证,在你的情况下你需要自己做。
However, at some point you need to trigger the validation of this POJO. If it were an @Entity
it would be your JPA provider which triggers validation, in your case you need to do it yourself.
有一个的很好的文档,它是JSR-303的参考实现。
There's a nice documentation for Hibernate Validator which is the reference implementation for JSR-303.
示例
public class Car {
@NotNull
@Valid
private List<Person> passengers = new ArrayList<Person>();
}
使用 Car
和验证:
Car car = new Car( null, true );
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );
您可能还想阅读(JPA,CDI等)。
You may also want to read how bean validation is integrated with other frameworks (JPA, CDI, etc.).
这篇关于使用Java EE 6 Bean验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!