Trapo. what do you think about ...

my journey developing trapo 
« Back to blog

Unique Constraint with Hibernate Validator: Harder Than You Think

I'm annotating my domain with Hibernate Validator's annotations then I notice that there is not an unique constraint. My first thought was: "not a big deal, for sure is a piece of cake implement it". I can't be more wrong. Actually, create a custom constraint that does not require database access is very simple. Just create the annotation, the validator class and you are done. But, for constraints that requires database access, such as unique that must execute a query against database to validate its uniqueness, it is a pain in the ass.

The problem is that your validators can't access sessionFactory or any other interface to the database. I know that I can break some rules and instantiate a sessionFactory/session/connection directly inside the Validator, but I dislike to do wrong things consciously. So, I looking for alternatives.

HIBERNATE VALIDATOR 4.0

The new version is already in beta state and it implements JSR 303 (Bean Validation). I have no problems using beta stuff, but, according to JSR 303 "@Unique cannot be tested at the Java level reliably but could generate a database unique constraint generation. @Unique is not part of the BV spec today."

Ouch. Next alternative.

HACK THE HIBERNATE VALIDATOR CODE

Not a real hack, but just replace ValidateEventListener class which requires create a new ClassValidator and a way to made validator know sessionFactory.

OTHER VALIDATION FRAMEWORKS

Maybe Spring Validation, maybe OVal or... I still looking.

Loading mentions Retweet

Comments (0)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    Connect    twitter