Implement validation in Spring Data REST.
Spring Data REST is a framework that helps developers to build hypermedia-driven REST web services. It is built on top of the Spring Data project and makes it easy to build hypermedia-driven REST web services that connect to Spring Data repositories – all using HAL as the driving hypermedia type.
In this article, we will look at how to implement validation in Spring Data REST.
There are two @Entity
classes, Author and Book. Both classes are accompanied by JpaRepository
classes - AuthorRepository and BookRepository.
While Author
and Book
are standard JPA entities, their repositories are annotated with @RepositoryRestResource
to expose them as REST resources.
link:src/main/java/zin/rashidi/boot/data/rest/book/AuthorRepository.java[role=include]
link:src/main/java/zin/rashidi/boot/data/rest/book/BookRepository.java[role=include]
We will implement a validation that ensures that Author
in Book
is not INACTIVE
. To do this, we will create a custom validator class, BeforeCreateBookValidator.
link:src/main/java/zin/rashidi/boot/data/rest/book/BeforeCreateBookValidator.java[role=include]
As we can see, the validator class implements Validator
interface and overrides supports
and validate
methods. The supports
method checks if the class is Book
and the validate
method checks if the Author
is INACTIVE
. Next we will inform Spring about our Validator
through BookValidatorConfiguration.
link:src/main/java/zin/rashidi/boot/data/rest/book/BookValidatorConfiguration.java[role=include]
Now, Spring is aware that the Validator
will be executed before creating a Book
.
We will perform a POST
request to create a Book
with an Author
that is INACTIVE
. The request will be rejected with 400 Bad Request
response.
link:src/test/java/zin/rashidi/boot/data/rest/book/CreateBookTests.java[role=include]
link:src/test/java/zin/rashidi/boot/data/rest/book/CreateBookTests.java[role=include]
Full implementation of the test can be found in CreateBookTests.