Create your first application with Spring Data REST

1. Introduction

Now that we understand what Spring Data is and its different modules, we will quickly go though a small demo on how to create a REST web service using Spring Data REST and Spring Data JPA.

Note that Spring Data REST is least bothered about the underlying Database technology you are using.

2. Implementation

To start creating the sample application, create a new Maven Project with with maven-archetype-webapp as archetype.

The first starting point is to configure the web.xml, where we specify the Spring context file details, from where the beans will get initialized. Secondly, RepositoryRestDispatcherServlet will be used instead of usual DispatcherServlet, to expose the configured REST Resources over HTTP.


The non-zero value of load-on-startup marks the servlet to be eagerly loaded during the web-container initialization.

web.xml

Update the pom.xml file –

pom.xml

We now have the dependencies added up. Let’s now create our entity.

User.java

Note the annotation that we have used to map the properties to their corresponding DB table columns. We will be using MySQL for this demo, and will define the configuration in our spring-config.xml.

spring-config.xml

component-scan on the specified package must contain the UserRepo class annotated with @RestRepositoryResource

So now, let’s create the UserRepo, which is actually a DAO interface, whose implementation we need not have to care about. This is one of the specialties of Spring Data.

UserRepo.java

Based on the above repo class, Spring Data internally generates the SQLs for you, without caring about the underlying database technology being used.

Note that we have specified a user search method, that searches a user based on their username. While specifying a repo method make sure of the following.

Spring Data Rest Repo

3. Running the application

Let’s now run the application by hitting the following URL –

http://localhost:8080/SpringDataRest/api/users/search/byName?name=test123

We can see the JSON output on the browser as –

4. Download source code

 

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.