Introduction about Bean Validation in Java

In the tutorial about @Entity and @Table annotation in JPA, I mentioned to you the concept of Java Bean, they are POJOs with at least one constructor with no parameters. We often use Java Bean to contain information of an object. To ensure that the object information contained in the Java Bean matches our needs, Java introduces the Java Bean Validation spec that makes it possible to validate the object’s information easily. How is it in details? We will learn about Bean Validation in Java in this tutorial.

First, I will create a new Maven project as an example:

Introduction about Bean Validation in Java

To work with Bean Validation, you need to declare the library implement this spec Hibernate Validator:

You will see that the API library defines the spec that is also included in the Maven Dependencies section of the project.

If you work with J2SE desktop applications, you need to declare an additional dependency as the Unified Expression Language (EL) as follows:

This library is used to evaluate the expression in the error message if we use it.

Now I have a Student class as follows:

Suppose now I need to store the information of the students with this Student class, which the student’s name is not null and the age of the student cannot be less than 18.

To satisfy this condition, I will use Bean Validation to define constraints when users want to add a new student as follows:

As you can see, here I use 2 annotations of Bean Validation @NotNull and @Min to define constraints for all student information. The message attribute in these two annotations is used to show to the user which value of the field is not correct.

You can find many other annotations in the spec page of the Bean Validation, here I only get these 2 annotations for example.

Now I will write an example to see how validation will happen.

First, I need to initialize ValidatorFactory object to retrieve Validator object as follow:

Suppose I have a student with the following information:

Then, use the validate() method of the Validator object:

you will see the following result:

Introduction about Bean Validation in Java

Because my age only set 12, this field is not right.

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment