HibernateValidator 5 seems to not cascade validation on JPA entities

巧了我就是萌 提交于 2019-12-08 04:22:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19855179/hibernatevalidator-5-seems-to-not-cascade-validation-on-jpa-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!