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();
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top