Validation across multiple layers
Hibernate Validator expresses constraints using annotations.
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int 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 Data repository 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.
Bean Validation reference implementation
Hibernate Validator is the reference implementation for the Bean 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.
Programmatic or automatic constraint validation
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 out Hibernate Validator in Quarkus.
Custom constraints
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 define custom constraints precisely capturing the semantics of application-specific types.
Rich metadata API
The Bean Validation metadata API facilitates tooling integration and metaprogramming. Naturally, Hibernate Validator goes beyond the spec. The programmatic constraint configuration API allows constraints to be created programmatically.
Compile-time type safety
The annotation-based approach is by nature quite type safe, but there’s even an annotation processor which raises compilation errors when constraint annotations are used incorrectly, for example, if the @Past
annotation is applied to a field of type String
.