Validation API - hudec/sql-processor GitHub Wiki
Validation API
Sample validator
The new features of the SQL Processor (SQLP) version 2.2.5 is the API for the input form validation, devoted for the CRUD statements (INSERT ant UPDATE)
The input data validation is the most common approach, how prevent DB from incorrect data seeding. There is lot of validation libraries, for example from Hibernate.
The SQLP doesn't have a goal to bring a new validator. Rather, using a smart API, it gives us a possibility to reuse any validation library. The SQLP knows, when the input value should be validated. On the other side, it delegates the validation process to the third library.
The validation API is
- SqlValidator - the most important interface for the validation process invocation
-
SqlValidatorFactory - the factory for
SqlValidator. It can cooperate with theSqlEngineFactory - SqlValidationContext - just a container for the interval validator representation
- SqlValidationResult - just a container for the internal validator result
- SqlValidationException - this exception is raised in INSERT/UPDATE statements in the case of any incorrect input data
The complete Javadoc
The sample presented this feature is the Simple HSQLDB. We are going to use the library hibernate-validator, so the next fragment should be located in pom.xml:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
This library works with validation annotations. The annotated POJO is located here pojo.qry. The annotations can be generated by the SQLEP automatically, if there's control directive pojogen-generate-validation-annotations; in definitions.qry.
At the end the sample validator is here SampleValidator. It works as a bridge between the SQLP and Hibernate validation library.
To activate this bridge, we can use for example the next code
JdbcEngineFactory factory = new JdbcEngineFactory();
...
factory.setValidatorFactory(new SampleValidator.SampleValidatorFactory());
Now we can test it. The attribute phoneNumber in POJO Contact is annotated as @Size ::: max 100, which in fact produces the next code in Contact.java
@Size(max = 100)
private String phoneNumber;
In the case we supply a too "long" phone number, the exception should be raised
contact = new Contact();
contact.setPhoneNumber("444-555-6666");
listc = main.getContactDao().list(contact);
c = listc.get(0);
c.setPhoneNumber("12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901");
try {
main.contactDao.update(c);
Assert.fail();
} catch (SqlValidationException ex) {
main.logger.warn(ex.getMessage());
}