I have a problem with Hibernate and Hibernate Validator 5. I have some entity, let's say Group
and another entity Person
. They are related as follows: Group has two references to Person - contact person and manager. They are both one-to-one relationships with full cascade and orphan removal options.
What I want is to validate the contact person and the manager while the group is being saved. The more, I want a different validation group to be used to validate contact person and manager. In order to do this, I placed @ConvertGroup(from = Default.class, to = ContactPersonValidation.class)
together with @Valid
before the contact person field and I did it analogously for manager field (using different validation group).
Now, Hibernate validation does not work - I mean that the group is not converted to the one provided in @ConvertGroup
. I followed the source code of Hibernate validator and it seems to validate Group object and two Person objects separately. Therefore, Person validation is not cascaded from Group object and the validation group is not converted.
Have you ever experienced a similar problem and know how to solve it?
During lifecycle validation triggered by JPA, Bean Validation uses a TraversableResolver
which doesn't follow up assocations also if they are marked with @Valid
(see 3.6.1.2 "Requirements for Automatic Validation upon Lifecycle Events" of the JPA 2.0 spec).
So your Person
objects won't be validated by following up references from Group
but they will be validated when they themselves are persisted. Thus the group conversions declared on Group
don't apply.
You can implement the behavior you want by defining a GroupSequenceProvider for Person
(note that this is a Hibernate Validator specific feature). For that purpose, you would have to pass the "role" of a person (e.g. in form of an enum with values Contact
and Manager
) to the Person
instances. The default group sequence provider could then access the role and apply one or the other validation group if a given Person
instance is persisted.