我目前正通过这种代码验证我的bean:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); validator.validateValue(class, propertyName, value);我的课程看起来像这样:
public static interface Primitive { public Primitive setString(String s); @NotNull public String getString(); }到目前为止这个工作正常。 但似乎普通的hibernate验证器不可能从给定的类中获取约束定义/映射,并添加如此处所述的其他约束。 看起来约束映射都是手动的,我不喜欢todo。 另一方面,我使用Validator.getConstraintsForClass(class)获得的BeanDescriptor似乎不能与ConstraintMapping一起使用。
这就是我的想法:
ConstraintMapping mapping = new ConstraintMapping(); mapping .type(Order.class).getConstraints()/*reads the constraints declared on the Bean*/ .property("customer", ElementType.FIELD)/*add additional constraints*/ .constraint(NotNullDef.class); Validator validator = Validation .byProvider(HibernateValidator.class) .configure() .addMapping(mapping) .buildValidatorFactory() .getValidator();I'm currently validating my beans through this kind of code:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); validator.validateValue(class, propertyName, value);My classes look like this:
public static interface Primitive { public Primitive setString(String s); @NotNull public String getString(); }This is working fine so far. But it seems that it's not possible with plain hibernate validator to get the Constraint Definitions/Mapping from a given Class and to add additional constraints like described here. It looks like the constraint mapping is all manual, which I don't like todo. On the other side the BeanDescriptor which I get with Validator.getConstraintsForClass(class) seems to be not usable with ConstraintMapping.
This is what I have in mind:
ConstraintMapping mapping = new ConstraintMapping(); mapping .type(Order.class).getConstraints()/*reads the constraints declared on the Bean*/ .property("customer", ElementType.FIELD)/*add additional constraints*/ .constraint(NotNullDef.class); Validator validator = Validation .byProvider(HibernateValidator.class) .configure() .addMapping(mapping) .buildValidatorFactory() .getValidator();最满意答案
程序性约束API已经是附加的,这意味着您不需要建议的getConstraints 。 另见Validator在线文档 - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-programmatic-api
默认情况下,通过流畅API添加的约束可添加到通过标准配置功能配置的约束。 但是也可以在需要时忽略注释和XML配置的约束。
The programmatic constraint API is already additive, meaning you don't need your suggested getConstraints. See also the Validator online docs - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-programmatic-api
By default, constraints added via the fluent API are additive to constraints configured via the standard configuration capabilities. But it is also possible to ignore annotation and XML configured constraints where required.
更多推荐
发布评论