I'm using JPA 2.0/Hibernate validation to validate my models. I now have a situation where the combination of two fields has to be validated:
public class MyModel {
public Integer getValue1() {
//...
}
public String getValue2() {
//...
}
}
The model is invalid if both getValue1()
and getValue2()
are null
and valid otherwise.
How can I perform this kind of validation with JPA 2.0/Hibernate? With a simple @NotNull
annotation both getters must be non-null to pass validation.
For multiple properties validation, you should use class-level constraints. From Bean Validation Sneak Peek part II: custom constraints:
You can also do using reflection. Here is the article that talks about implementing this using reflection.
http://dolszewski.com/java/cross-field-validation/
A class level validator is the way to go, when you want to stay with the Bean Validation specification. If you are happy to use a Hibernate Validator feature, you could use @ScriptAssert, which is provided in Validator-4.1.0.Final.
To work properly with Bean Validation, the example provided in Pascal Thivent's answer could be rewritten as follows: