包含具有不同组接口的bean的多个bean验证

时间:2011-10-06 14:46:35

标签: java hibernate validation

我在验证非常特定的bean时遇到问题。 我先告诉你一些代码:

@Entity
@Table(name = "customers", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = {"cus_email" }))
public class Customers extends ModelObject implements java.io.Serializable {

    private static final long serialVersionUID = -3197505684643025341L;

    private long cusId;
    private String cusEmail;
    private String cusPassword;
    private Addresses shippingAddress;
    private Addresses invoiceAddress;

    @Id
    @Column(name = "cus_id", unique = true, nullable = false)
    @SequenceGenerator(name = "cus_seq", sequenceName = "customers_cus_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cus_seq")
    @NotNull
    public long getCusId() {
        return cusId;
    }

    public void setCusId(long cusId) {
        this.cusId = cusId;
    }

    @NotEmpty
    @Size(min=5, max=255)
    @Email
    @Column(name = "cus_email", unique = true, nullable = false, length = 255)
    public String getCusEmail() {
        return cusEmail;
    }

    public void setCusEmail(String cusEmail) {
        this.cusEmail = cusEmail;
    }

    @NotNull
    @Column(name = "cus_password", nullable = false)
    public String getCusPassword() {
        return cusPassword;
    }

    public void setCusPassword(String cusPassword) {
        this.cusPassword = cusPassword;
    }

    @NotNull
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cus_shipping_adr_id", nullable = false)
    @Cascade(value = CascadeType.ALL)
    @Valid
    public Addresses getShippingAddress() {
        return shippingAddress;
    }

    public void setShippingAddress(Addresses cusShippingAddress) {
        this.shippingAddress = cusShippingAddress;
    }

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cus_invoice_adr_id", nullable = true)
    @Cascade(value = CascadeType.ALL)
    @Valid
    public Addresses getInvoiceAddress() {
        return invoiceAddress;
    }

    public void setInvoiceAddress(Addresses cusInvoiceAddress) {
        this.invoiceAddress = cusInvoiceAddress;
    }
}

如您所见,我这里有两个地址字段 - 一个用于发货地址,另一个用于发票地址 每种类型地址的验证应该是不同的,例如,我在发货地址不需要增值税号码,但我可能需要在发票中注明。

我使用小组对发票地址和送货地址执行不同的验证,如果我手动验证地址字段,则可以正常工作。

但现在我想用地址验证整个Customer对象(如果有的话) 我尝试使用以下代码执行此操作:

    private void validateCustomerData() throws CustomerValidationException {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Customers>> constraintViolations;
        constraintViolations = validator.validate(customer, Default.class, InvoiceAddressCheck.class, ShippingAddressCheck.class);
        if (!constraintViolations.isEmpty()) {
            throw new CustomerValidationException(3, Message.CustomerDataException, constraintViolations);
        }
    }


当然这不会像它想象的那样工作,因为两个验证都在客户对象内的地址对象的两个实例上运行,所以我从InvoiceAddressCheck接口的发货地址和ShippingAddressCheck的发票地址错误中得到错误。

以下是地址bean的缩写声明:

@Entity
@Table(name = "addresses", schema = "public")
@TypeDef(name = "genderConverter", typeClass = GenderConverter.class)
public class Addresses extends ModelObject implements Serializable{

        private static final long serialVersionUID = -1123044739678014182L;

        private long adrId;
        private String street;
        private String houseNo;
        private String zipCode;
        private String state;
        private String countryCode;
        private String vatNo;
        private Customers customersShipping;
        private Customers customersInvoice;

        public Addresses() {}

        public Addresses(long adrId) {
            super();
            this.adrId = adrId;
        }

        @Id
        @Column(name = "adr_id", unique = true, nullable = false)
        @SequenceGenerator(name = "adr_seq", sequenceName = "adr_id_seq", allocationSize = 1)
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "adr_seq")
        @NotNull
        public long getAdrId() {
            return adrId;
        }

        public void setAdrId(long adrId) {
            this.adrId = adrId;
        }

        @NotNull
        @Column(name = "adr_street", nullable = false)
        public String getStreet() {
            return street;
        }

        public void setStreet(String street) {
            this.street = street;
        }

        @NotEmpty(groups = ShippingAddressCheck.class)
        @Column(name = "adr_house_no")
        public String getHouseNo() {
            return houseNo;
        }


        @NotEmpty(groups = ShippingAddressCheck.class)
        @Column(name = "adr_zip_code")
        public String getZipCode() {
            return zipCode;
        }

        public void setZipCode(String zipCode) {
            this.zipCode = zipCode;
        }

        @Column(name = "adr_vat_no")
        @NotEmpty(groups = InvoiceAddressCheck.class)
        public String getVatNo() {
            return vatNo;
        }

        public void setVatNo(String vatNo) {
            this.vatNo = vatNo;
        }

        @OneToOne(fetch = FetchType.LAZY, mappedBy = "shippingAddress")
        public Customers getCustomersShipping() {
            return customersShipping;
        }

        public void setCustomersShipping(Customers customersShipping) {
            this.customersShipping = customersShipping;
        }

        @OneToOne(fetch = FetchType.LAZY, mappedBy = "invoiceAddress")
        public Customers getCustomersInvoice() {
            return customersInvoice;
        }

        public void setCustomersInvoice(Customers customersInvoice) {
            this.customersInvoice = customersInvoice;
        }
    }


有没有办法运行验证,以便使用InvoiceAddressCheck组验证invoiceAddress,并使用ShippingAddressCheck组验证shippingAddress,但在验证Customer对象期间运行? 我知道我可以为每个子对象手动完成,但这不是这里的重点。

1 个答案:

答案 0 :(得分:1)

现在临时解决方案是为发票字段编写自定义验证,因此它仅检查InvoiceAddressCheck 这是我的代码

译注:

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {InvoiceAddressValidator.class })
public @interface InvoiceAddressChecker {
    String message() default "Invoice address incorrect.";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

验证:

public class InvoiceAddressValidator implements ConstraintValidator<InvoiceAddressChecker, Addresses> {

    @Override
    public void initialize(InvoiceAddressChecker params) {
    }

    @Override
    public boolean isValid(Addresses invoiceAddress, ConstraintValidatorContext context) {
        // invoice address is optional
        if (invoiceAddress == null) {
            return true;
        }
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Addresses>> constraintViolations;
        constraintViolations = validator.validate(invoiceAddress, Default.class, InvoiceAddressCheck.class);
        if (constraintViolations.isEmpty()) {
            return true;
        } else {
            context.disableDefaultConstraintViolation();
            Iterator<ConstraintViolation<Addresses>> iter = constraintViolations.iterator();
            while (iter.hasNext()) {
                ConstraintViolation<Addresses> violation = iter.next();
                context.buildConstraintViolationWithTemplate(violation.getMessage()).addNode(
                        violation.getPropertyPath().toString()).addConstraintViolation();
            }
            return false;
        }
    }
}

模型注释:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cus_invoice_adr_id", nullable = true)
@Cascade(value = CascadeType.ALL)
@InvoiceAddressChecker
public Addresses getInvoiceAddress() {
    return invoiceAddress;
}

这不是一个很好的解决方案,但它可以满足我的需求。 如果你找到更好的解决方案,请告诉我:))