Hi, I'm Thorben Janssen from thoughts-on-java.org
with a new Hibernate Tip.
And today I want to show you the best approach to
automatically validate the value of an entity attribute
before persisting it.
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
and annotate the attribute with the BeanValiation annotations
Let's get into the IDE and have a closer look at it.
Here you can see the required maven dependencies to add Hibernate Validator to your project.
You need the project itself
and the Expression Language API with its implementation.
After you've added the dependencies, you can define the validation.
In this example, I annotate the entity attribute with a @Min
and a @Max annotation
to define the lower and upper boundary of the valid range.
So, here the numPages attribute
has to have a value between 100 and 1000.
When you now try to persist a Book entity,
Hibernate will trigger the validation.
And if the value of numPages is outside of the allowed range,
Hibernate Validator throws an exception.
You can see the error message here.
OK, that's it for today.
If you want to learn more about Hibernate,
you should join the free Thoughts on Java Library.
It gives you free access to a lot of member-only content
like an ebook about the Java 8 support in Hibernate,
a printable PDF version of this Hibernate Tip,
lots of cheat sheets and a video course.
I'll add the link to it to the video description below.
See you next week for a new Hibernate Tip
and if you like today's video,
please give it thumbs up and subscribe below.
Bye
No comments:
Post a Comment