Spring Data Rest

Spring Data Rest provides a very simple option to expose CRUD RESTful services around data repositories.

Some of the important features of Spring Data Rest include the following:

  • Exposing the REST API around Spring Data repositories
  • Support for pagination and filtering
  • Understanding query methods in Spring Data repositories and exposing them as search resources
  • Among the frameworks supported are JPA, MongoDB, and Cassandra
  • Options to customize the resources are exposed by default

We will start by including the Spring Boot Data Rest starter in our pom.xml:

    <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

We can make UserRepository expose the REST service by adding a simple annotation, as shown in the following snippet:

    @RepositoryRestResource(collectionResourceRel = "users", path =
"users")
public interface UserRepository
extends PagingAndSortingRepository<User, Long> {

Important things to note are as follows:

  • @RepositoryRestResource: The annotation used to expose a repository using REST
  • collectionResourceRel = "users": The collectionResourceRel value to be used in the generated links
  • path = "users": The path under which the resource has to be exposed

When we launch SpringDataJpaFirstExampleApplication as a Java application, the following can be seen in the log:

s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto ****
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}], methods=[OPTIONS]
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}], methods=[HEAD]
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}], methods=[GET]
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}], methods=[POST]
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}], methods=[OPTIONS]
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}]
o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search], methods=[GET]

The preceding log shows that the Spring MVC DispatcherServlet is launched and ready to serve different request methods and URIs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset