Accessing the Hibernate Session within a ConstraintValidator

Here are all the pieces you need to write a ConstraintValidator which has access to the Hibernate Session respectively Hibernate EntityManager. This example will implement a @Unique constraint as discussed in HV-230. The reason @Unique is not part of the built-in constraints is the fact that accessing the Session/EntityManager during a valiation is opening yourself up for potenital phantom reads. Think twice before you go for the following approach.

First you will need a custom ConstraintValidatorFactory. This factory has a handle to the Hibernate SessionFactory in order to inject it when a new ConstraintValidator is created.