DTOs with Lombok and Bean Validation
If you are working with legacy databases it can be inconvenient to use an ORM framework, like Hibernate, and you find yourself writing huge data transfer objects (DTOs) for data mapper frameworks like MyBatis (my personal favorite). Such DTOs include lots of boiler-plate code that can be removed with the very useful annotations from Project Lombok. The following is a simple example of what Lombok can do:
With the Lombok annotation @Data this will generate code equal to:
This is all really nice and Lombok is a very powerful tool. However it can be even better! With the introduction of bean validation in JEE 6 (JSR-303) we can now check database constraints on-the-fly by annotating the DTOs. Here is an example:
That is, id must be 0 or greater, firstName must be between 2 and 8 chars and lastName must not be null.
If you got several databases with different constrains it is really a nice feature to check the constraints in the DTOs or other data beans.
In order to do the actual validation you need to call a Validator with the annotated, injected (use CDI) bean, like this:
Where someBean has been injected using CDI, e.g.:
Project Lombok does not add any JARs to your classpath, as it is pure compile-time, thus the above is all standard JEE 6.