0
votes

I've looked on Internet but I could not find any example on JSR 303 that solve my problem.

Suppose you have the following classes (this design cannot be changed!) :

A person who has a domicile and a correspondence address is represented as follows :

public class Person {

    private Address domicile = null;
    private Address correspondence = null;


    public Address getDomicile() {
        return domicile;
    }

    public void setDomicile(final Address domicile) {
        this.domicile = domicile;
    }

    public Address getCorrespondence() {
       return correspondence;
    }

    public void setCorrespondence(final Address correspondence) {
      this.correspondence = correspondence;
    }

}

public class Address {

  private String streetName = null;

  public String getStreetName() {
    return streetName;
  }

 public void setStreetName(final String streetName) {
    this.streetName = streetName;
 }

}

How can I implement, using JSR 303 approach, a rule saying that the streetName must not be empty if it refers to domicile address ?

e.g. Running a validation like this I should get a validation failure (street for domicile address is null) :

Person p = new Person();

Address a = new Address();
a.setStreetName("some street");
p.setCorrespondence(a);

a = new Address();
p.setDomicile(a);

validator.validate(p);

The validator is invoked against the bean Person. According to this design, I think that I should define some annotation on the 2 Addresses instances (within Person class) and in some how this information should be passed down to some constraint defined on the streetName field itself (e.g. NotBlank) but I don't know how to do so.

I am aware of JSR 303 groups technique but it doesn't seem suitable to my special requirement.

1

1 Answers

0
votes

The solution would be to write custom validator, which will be applied at the level of Person class.

@ValidateAddress
public class Person {

    private Address domicile = null;
    private Address correspondence = null;

    //....
}

Such validator would have access to both fields and could validate that which is not null.