9. Enforcing Attribute Validity Checks
A Validity check is a set of parameters that define the validity of an attribute value. Validity checks are defined as part of an application schema using the mapping tool. The persistence layer does not automatically enforce validity checks. It is up to your code to test validity and to take appropriate action when a validity check fails.
To check whether the attribute values of an object pass all validity checks, you use the checkValidity() method of the Database class. This method accepts as argument the object to be checked and throws a BOValidityCheckException exception if one or more attributes in the supplied object fail the validity checks. The BOValidityCheckException object contains the name of the invalid attribute and a reason code. Reason codes are defined in the BOP_ACheck class. The exception thrown corresponds to the first attribute which failed the check. Exceptions for additional invalid attributes are chained to the first one and can be retrieved using the getNext() method of the BOValidityCheckException object.
Below is an example that checks the validity of a new Contact object. Assuming that a
required last name validity check has been defined, an exception is thrown when the checkValidity() method is invoked:
Contact newCt = (Contact)db.create(Contact.class);
newCt.setFirstName("MIKE");
newCt.setSecondName(null);
newCt.setTitle("MR.");
try {
db.checkValidity(newCt);
db.update(newCt); //never gets here
} catch (BOValidityCheckException ctex) {
System.out.println("Missing last name! Object not saved.");
}
Additional examples are provided in the ContactApp class of the vcontactdemo sample application.