Validations
Spring Boot
In every application we build it’s always necessary
to validate data, and with Spring Boot, it got you
covered!
@mauricioperez
@mauricioperez
Validations in
01
Spring Boot
When validating data in a Spring Boot application,
we can reach it from different approaches. But
the main character comes when we integrate this
dependecy into our pom.xml
You can get this dependency from the Spring
Starter.
Also remember that by integrating this
dependency, you are using the de-facto
hibernate validations from hibernate.validator
@mauricioperez
Hibernate for
02
validating??
Yeah you heard it right! Hibernate also helps us to
validate data and not merely treating it with the
persistence stuff it normally offers.
The Hibernate’s team has built a strong library
where we can reach through the annotations
offered just to implement into our code and they
will run and execute like magic in regards of the
data integrity.
But yes, when we want to implement that kind of
persistence stuff, you know it already: just
implement Spring Data JPA module in your
Spring Boot project, and you are good to go!
@mauricioperez
Annotations to
03
validate date
Here you have the most important built-in
annotations that you can leverage for your
project:
1. @NotNull
2. @AssertTrue
3. @Size
4. @Min
5. @Max
6. @Email
7. @NotEmpty
8. @NotBlank
9. @Positive and @PositiveOrZero
10. @Past and @PastOrPresent
11. @Future and @FutureOrPresent
@mauricioperez
Approaches of
04
validation
1. In a database entity and you want to validate
each field
resource extracted from https://www.baeldung.com/java-validation
@mauricioperez
Approaches of
05
validation
Also we can apply it to data structures in
order for whenever we want to add
specific data into a list, for instance, all of
the data inside will be hence, validated.
resource extracted from https://www.baeldung.com/java-validation
@mauricioperez
A special
06
approach
And for those who might asked: “What
about REST APIs?” Yes I got you covered
too! And here you can validate through a
Controller approach, but first you have to
mix the validation via the component or
entity and you have to add in the
controller’s parameter’s method a @Valid
annotation before the instance that will
be receiving the data in the form of the
entity coming from the request.
@mauricioperez
A special
07
approach
For instance, let’s say you want to add a
user, but you have your user’s entity
covered with a lot of constraints; once
you get the body’s request coming with
data aimed to be filled to the user’s entity
you apply the following movement:
Thank you!
@mauricioperez
Validations in Spring Boot are
always easy to implement, but
sometimes might be tricky!