From the course: Learning Java Enterprise Edition

Bean Validation in practice - Java EE Tutorial

From the course: Learning Java Enterprise Edition

Start my 1-month free trial

Bean Validation in practice

- [Instructor] To see the bean validation action, let's go back to the cargo object and explore how it and its dependencies use bean validation to maintain data integrity. Okay, let's get started. Okay, so here we have the cargo object again. Let's have a look at the route specification entity. Here you can see an example of not null bean validation constraint on the arrival deadline. This says that the arrival deadline must not be null; and when you think about it, this is actually quite a logical constraint. A route must have an expected date of arrival. Let's dig a little further and go into the origin field and look at the location object. Here you can see we have another field annotated not null and again it is logical that a location has a name. Let's go one step further and look into the unLocode field. Here you can see another not null annotation and also a pattern constraint. This is an example of the use of regular expressions to state the constraint. Also notice that we are using more than just one constraint. Here we are saying that the unLocode must be not null and must match the pattern specified in the bean validation. So when are these bean validations performed? To see this we need to go back to the JPA cargo repository. When the entity manager .persist is executed, the JPA will inspect all bean validation annotations in the cargo entity and all its embedded entities and evaluate each and every one of these constraints; and if any constraint fails, an exception is thrown. And in the same fashion, this same evaluation will take place when provoked by JSF, JAX-RS, CDI and when validated manually by the validator factory.

Contents