Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
The value of one of the attributes of my entity has to be within a defined range. What is the best approach to automatically validate the attribute value before persisting it?
Don’t want to read? You can watch it here!
The Bean Validation Specification and its reference implementation Hibernate Validator provide easy to use and powerful validation options. It integrates with JPA and Hibernate ORM so that it triggers the validation for all entity attributes before persisting or updating an entity.
It only takes 2 steps to automatically validate that the value of an entity attribute is within a defined range. You need to:
- add the required dependencies to your project
- annotate the attribute with the BeanValiation annotations
You need to add the following maven dependencies to your project.
In the next step, you need to define the validation. In this example, you need to annotate the entity attribute with @Min and @Max to define the lower and upper boundary of the valid range.
You can see an example of it in the following code snippet. It checks that the numPages attribute has a value between 100 and 1000.
When you now try to persist a Book entity and the value of numPages is outside of the allowed range, Hibernate Validator throws one of the following exceptions.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
You can do a lot more than just the simple validation I showed in this Hibernate Tips. I explain the BeanValidation integration in more detail in How to automatically validate entities with Hibernate Validator.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.