HibernateValidator约束为嵌套对象结构内部的字段映射

问题描述 投票:1回答:1

我下面有来自第三方jar的java外部类,我想针对该类进行bean验证。

**Product.java:**

private String id;
private Boolean active;
private Price price

**Price.java**

private String discountPrice;
private String originalPrice;

下面是相同的休眠验证器

private Validator createMiraklOfferDataValidator() {
        HibernateValidatorConfiguration hibernateValidatorConfiguration = Validation
            .byProvider( HibernateValidator.class )
            .configure();
        ConstraintMapping constraintMapping = hibernateValidatorConfiguration.createConstraintMapping();
        constraintMapping
            .type( Product.class )
            .field("id")
                .constraint(new NotNullDef().message("id should not be null"))

            .field("active")
                .constraint(new NotNullDef())


            .type( Price.class )
                .field("originalPrice")
                    .constraint(new NotNullDef().message("originalPrice should not be null"))

                .field("discountPrice")
                    .constraint(new NotNullDef().message("discountPrice should not be null"))


        Validator validator = hibernateValidatorConfiguration.addMapping(constraintMapping)
            .buildValidatorFactory()
            .getValidator();
        return validator;
    }

对于Price的嵌套类,验证未按预期进行,非常感谢您的帮助。

java bean-validation nhibernate-validator
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.