Spring Data REST Tutorial

In this tutorial, we will learn how to use the Spring Data REST module to create REST endpoints.

Spring Data REST is part of the umbrella Spring Data project and makes it easy to build hypermedia-driven REST web services on top of Spring Data repositories.

Spring Data REST builds on top of Spring Data repositories, analyzes your application’s domain model, and exposes hypermedia-driven HTTP resources for aggregates contained in the model.

Problem and Solution

What is the Problem?

In a typical Spring-based application, we create three-layer architecture as below:

spring data rest tutorial - java guides

If we want to create a CRUD REST APIs for an entity then we need to create a controller class and need to manually write REST APIs ( create, update, delete, get, pagination, sorting etc).

If we want to create a CRUD REST APIs for another entity: For example, Department, Project, Company, User, etc. Then, we need to create a controller for all these entities and create REST APIs.

We are repeating the same code again….
Think about the solution : Spring can Create CRUD REST APIs for entity automatically for us

Solution

Spring Data REST module is the solution. Spring Data REST uses interfaces that extend JpaRepository and provides CRUD REST APIs for entities for FREE - Helps to minimize the boiler-plate controller layer code.
spring data rest tutorial - java guides

1. Create Spring Boot Project

Spring Boot provides a web tool called https://start.spring.io to bootstrap an application quickly. Just go to https://start.spring.io and generate a new spring boot project.

Use the below details in the Spring boot creation:

Project Name: spring-data-rest-tutorial

Project Type: Maven

Choose dependencies:  REST Repositories, Spring Data JPA, H2 database, Lombok

Package name: net.javaguides.springdatarest

2. Maven Dependencies

Here is the complete pom.xml for your reference:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>net.javaguides</groupId>
	<artifactId>spring-data-rest-tutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-data-rest-tutorial</name>
	<description>Demo project for Spring Boot and Spring Data REST</description>
	<properties>
		<java.version>8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

3. Create JPA Entity

Let's create an entity package inside a base package "net.javaguides.springdatarest". Within the entity package, create a User class with the following content:
package net.javaguides.springdatarest.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;


@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(
            name = "first_name", nullable = false
    )
    private String firstName;

    @Column(
            name = "last_name"
    )
    private String lastName;

    private String email;
}
Note that we are using Lombok annotation @Data to reduce the boilerplate code (getters/setters).

4. Create Spring Data JPA Repository

The next thing we’re gonna do is create a repository to access a User’s data from the database.

The JpaRepository interface defines methods for all the CRUD operations on the entity, and a default implementation of the JpaRepository called SimpleJpaRepository.

Let's create a repository package inside a base package "net.javaguides.springdatarest". Within the repository package, create a UserReposity interface with the following content:
package net.javaguides.springdatarest.repository;

import net.javaguides.springdatarest.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}
That's it. Spring Data REST will create REST APIs based on the entity type. We no need to create controller layer implementation.

5. Test REST APIs using Postman

Test GET All Users:

HTTP Method: GET

Test GET User By ID:

HTTP Method: GET

Test POST User:

HTTP Method: POST

Test PUT User:

HTTP Method: PUT

Test DELETE User:

HTTP Method: DELETE

6. Change REST API Path

You can use @RepositoryRestResource annotation to change the path from /users to /members:
package net.javaguides.springdatarest.repository;

import net.javaguides.springdatarest.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource(path = "members")
public interface UserRepository extends JpaRepository<User, Long> {

}

7. Pagination and Sorting Support

Pagination:


Sorting:


8. REST API for Query Methods

Let's create a query method in the below repository and test using the postman client:

package net.javaguides.springdatarest.repository;

import net.javaguides.springdatarest.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource(path = "members")
public interface UserRepository extends JpaRepository<User, Long> {

    List<User> findByFirstName(@Param("firstName") String firstName);

}

9. Source code on GitHub

Comments