Validating Multiple Fields in Combination
In JPA 2.0/Hibernate, simple @NotNull annotations on multiple fields will only validate individual fields. To validate a combination of fields, consider using class-level constraints.
As described in the Bean Validation Sneak Peek part II: custom constraints, class-level constraints allow validation logic to be applied across multiple properties within an object. This is particularly useful for complex validation rules that depend on multiple fields.
Implementation
To implement class-level constraints, define an annotation (@AddressAnnotation) and a constraint validator (MultiCountryAddressValidator). The annotation specifies the validation rule to be applied, while the validator implements the logic for validating the combination of fields.
@AddressAnnotation public class Address { @NotNull @Max(50) private String street1; @Max(50) private String street2; @Max(10) @NotNull private String zipCode; @Max(20) @NotNull String city; @NotNull private Country country; } public class MultiCountryAddressValidator implements ConstraintValidator<AddressAnnotation, Address> { public boolean isValid(Address object, ConstraintValidatorContext context) { // Validate zipcode and city depending on the country // ... } }
In the validator, the object instance is passed to the isValid method, allowing access to all fields for validation purposes. The validator can check the interdependencies between fields, such as the correlation between zip code and city.
Usage
Once defined, the class-level constraint can be applied to the model class using the annotation:
@AddressAnnotation public class MyModel { public Integer getValue1() { //... } public String getValue2() { //... } }
This annotation indicates that the MultiCountryAddressValidator should be used to validate the combination of getValue1() and getValue2(). If both fields are null, the model is considered invalid. Otherwise, the model is valid.
The above is the detailed content of How to Validate Multiple Fields in Combination in JPA 2.0/Hibernate?. For more information, please follow other related articles on the PHP Chinese website!