Migrating from Traditional DAO to Spring Data REST with JPA



Spring Data Rest is a spring boot project but it's like a more advanced and less coding application. There are three new concepts in Spring Data Rest -  

  • Configuration 

It adds 's' automatically to the entity. You can also give path for your URL 

Add @RepositoryRestResource(path="members") annotation at top of Repository interface.


  • Pagination 

# change default page size 

spring.data.rest.default-page-size=3 


  • Sorting 

http://localhost:8080/magic-api/members?sort=age ---default in ascending 

http://localhost:8080/magic-api/members?sort=age ---in descending


Steps to develop CRUD application-  


  1. Go to https://start.spring.io/ and kick start your project. Add necessary dependencies like Spring Data JPA, Spring Web, Spring Boot DevTools, MySql Driver, spring-boot-starter-data-rest. Select as maven and enter.  


  1. Import as maven project and check pom for dependencies we added. 


  1. Create entity class in entity package and write the required code with annotations, getters and setters, toString() and constructors.   


  1. Create a JpaRepository interface extending “org.springframework.data.jpa.repository.JpaRepository<T, ID>” extension. After this just replace <T, ID> with <Entity_name, Integer>, Add @RepositoryRestResource(path="members") annotation at top of Repository interface.


  1. In resources>application.properties file add the highlighted code below in your existing CURD properties code 

spring.datasource.url=jdbc:mysql://localhost:3306/employee_directory?useSSL=false 

spring.datasource.username=root 

spring.datasource.password=root 

spring.datasource.hikari.maximum-pool-size=100 

spring.datasource.hikari.minimum-idle=10 

  

spring.jpa.show-sql=true 

logging.level.web=DEBUG 

  

# Spring Data Rest Properties 

spring.data.rest.base-path=/magic-api   //for url path use magic-api/members 

# change default page size 

spring.data.rest.default-page-size=20 

 

 

  1. After doing the necessary coding in the above classes, run the project as an application and after it is up in IDE, check localhost:8080/ in Browser.  

  

  1. Do CRUD operations in postman with the same URL from the browser and verify from the database.  

 

http://localhost:8080/employees 

 

GET- http://localhost:8080/magic-api/employees 

POST- http://localhost:8080/magic-api/employees 

PUT- http://localhost:8080/magic-api/employees/13 

DELETE- http://localhost:8080/magic-api/employees/13 

  

  1. Find the code, postman collections and SQL query here: https://github.com/Leaf-Co-Kb/Employee-Managment-Data-Rest.  

Comments

Popular posts from this blog

Depression-A life taking mind disorder

Benefits of Giloy or Tinospora