Damian Walczak
Damian Walczak

Reputation: 1334

Multiple beans validation inside containing bean with different group interfaces

I have problem with validation a very specific beans. Let me give you some code first:

@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;
    }
}

As you can see, I have here two address fields - one for shipping address, the other for invoice address.
The validation for each type of address should be different, as e.g. I don't need VAT number in shipping address, but I may want that in invoice.

I used groups to perform different validation on invoice address and shipping address which works OK if I do manual validation of address field.

But now I'd like to validate whole Customer object with addresses (if available).
I tried to do that with code below:

    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);
        }
    }


Of course this doesn't work as it supposed, since both validations are run on both instances of address objects inside customer object, so I get errors in shipping address from InvoiceAddressCheck interface and errors in invoice address from ShippingAddressCheck.

Here is shortened declaration of Addresses 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;
        }
    }


Is there any way to run the validation, so that invoiceAddress is validated with InvoiceAddressCheck group and shippingAddress validated with ShippingAddressCheck group, but run during validation of Customer object?
I know that I can do it manually for each subobject, but that is not the point in here.

Upvotes: 3

Views: 1386

Answers (1)

Damian Walczak
Damian Walczak

Reputation: 1334

Temp solution for now is to write custom validation for invoice field, so it checks only InvoiceAddressCheck.
Here is the code I have

Annotation:

@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 {};
}

Validator:

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;
        }
    }
}

And model annotation:

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

It's not really great solution, but it does what I need. If you figure out better solution, please let me know :)

Upvotes: 1

Related Questions