How to access data from Database with Spring Data Rest

How to access data from the Database with Spring Data Rest? In this article, we will see an example to access data from a Database with Spring Data Rest?

Spring Data Rest is part of the umbrella Spring Data project. If you want to expose HATEOS RESTFUL resources around the Spring Data repository we can use Spring Data Rest.

Access data from Database with Spring Data Rest

Here, we will fetch the data from the Spring Data Repository interface without using the Controller and Service class.

Tools and Technologies:

  • Spring Tool Suite IDE/IntelliJ IDEA
  • MYSQL database.
  • Spring Boot.
  • Add Spring Data Rest Dependency

Create Project

Create a project using Spring Initializr. If you don’t know how to create a project using the same check this article

Import a Project

Now, it’s time to import the project into STS. Go to File > Import > Maven > Existing Maven Project > Next > Browse > Select the project > Finish. Now it will take time to import the project and will import all the dependencies.

Add this dependency inside the pom.xml file


Configure application. properties file

# change the port

#Database Configrations
spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto = update

Create Category Model Class

package com.example.AccessDataFromJPA.model;

import lombok.Data;

import javax.persistence.*;

@Table(name = "category_table")
public class Category {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String categoryName;
    private String categoryDescription;


Create Category Repository

Here, we need to use @RepositoryRestResource annotation to build the RESTAPI repository. (If it is showing an error it means you have not added the spring-boot-starter-data-rest dependency)

package com.example.AccessDataFromJPA.dao;

import com.example.AccessDataFromJPA.model.Category;

@RepositoryRestResource(collectionResourceRel = "category", path = "category")
public interface CategoryRepository extends JpaRepository<Category,Long> {


Run the class.

package com.example.AccessDataFromJPA;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class AccessDataFromJpaApplication {

 public static void main(String[] args) {, args);


Now, insert some data into the category_table which will be created inside your MYSQL database.

Go to the browser/POSTMAN app and type localhost:8888/category. You will be able to see the response in the form of JSON.

In this way, we can access data from the MYSQL database using Spring Data Rest.