Hibernate Validator expresses constraints using annotations.
publicclassCar {
@NotNull
privateString manufacturer;
@NotNull
@Size(min =2, max =14)
privateString licensePlate;
@Min(2)
privateint seatCount;
// ...
}If necessary, the constraints may be overridden in XML.
Such constraints are not tied to a specific architectural tier, programming model, or framework.Constraints might apply to entity classes, Jakarta Datarepository methods, or Jakarta RESTful web service endpoints.And Validator is not tied to the server—it works just as well for client-side Java programming.
Hibernate Validator is the reference implementation for theBean Validation specification.Indeed, the original specification was inspired by an early version of Hibernate Validator.
Bean Validation is an integral part of the Jakarta platform, incorporated by the Persistence, Data, RESTful Web Services, MVC, and Faces specifications, and by that black sheep of the Hibernate family,CDI.
Constraints may be validated programmatically, but many Java frameworks and libraries—including Hibernate ORM—feature built-in support for Bean Validation, making it easy to enforce the constraints completely declaratively.
For example, a constraint is validated automatically if it applies to:
a field of an entity class,
a parameter of a repository method, or
a parameter of a RESTful web service endpoint.
To see all this in action, you can try outHibernate Validator in Quarkus.
The Bean Validation standard specifies a range of predefined constraint types, and Hibernate Validator adds even more, even including some country-specific constraint types such as@TituloEleitoral.
But the true power of Bean Validation lies in how easy it is to definecustom constraints precisely capturing the semantics of application-specific types.
The Bean Validationmetadata API facilitates tooling integration and metaprogramming.Naturally, Hibernate Validator goes beyond the spec.Theprogrammatic constraint configuration API allows constraints to be created programmatically.
The annotation-based approach is by nature quite type safe, but there’s even anannotation processor which raises compilation errors when constraint annotations are used incorrectly, for example, if the@Past annotation is applied to a field of typeString.