Question
How can I validate the combination of two fields in a JPA 2.0 model?
public class MyModel {
private Integer value1;
private String value2;
public Integer getValue1() {
return value1;
}
public String getValue2() {
return value2;
}
}
Answer
In JPA 2.0/Hibernate, conditional validation on field combinations can be achieved by implementing custom validation. This allows you to define complex validation logic beyond the standard annotations.
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
@Constraint(validatedBy = MyModelValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidMyModel {
String message() default "Either value1 or value2 must be non-null.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class MyModel {
private Integer value1;
private String value2;
@ValidMyModel
public Integer getValue1() {
return value1;
}
public String getValue2() {
return value2;
}
}
public class MyModelValidator implements ConstraintValidator<ValidMyModel, MyModel> {
@Override
public boolean isValid(MyModel model, ConstraintValidatorContext context) {
return (model.getValue1() != null || model.getValue2() != null);
}
}
Causes
- If both fields are null, the model should be considered invalid, but using standard @NotNull annotations makes both fields checked independently.
Solutions
- Create a custom validation annotation that checks the logic for both fields together.
- Implement a validator class that contains the validation logic for the combination of the fields.
Common Mistakes
Mistake: Not implementing the 'isValid' method correctly in the custom validator.
Solution: Ensure that the logic checks for the combination of fields correctly. Only one of the fields should not be null for the validation to pass.
Mistake: Forgetting to annotate the class with custom validation.
Solution: Make sure the model class is annotated with the newly created @ValidMyModel annotation.
Helpers
- JPA validation
- Hibernate validation
- custom validation annotation
- field combination validation in Hibernate
- JPA model validation