Spring Boot JpaRepository with Example

28 Dec, 2021
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:
It allows avoiding heavy configuration of XML which is present in spring
It provides easy maintenance and creation of REST endpoints
It includes embedded Tomcat-server
Deployment is very easy, war and jar files can be easily deployed in the tomcat server
For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use JpaRepository to manage data in a Spring Boot application.
JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting.
Syntax:
public interface JpaRepository<T,ID> 
extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>  
Where:
T: Domain type that repository manages (Generally the Entity/Model class name)
ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)
Illustration:
public interface DepartmentRepository extends JpaRepository<Department, Long> {}
Some of the most important methods that are available inside the JpaRepository are given below
Method 1: saveAll(): Saves all given entities.
Syntax:
<S extends T> List<S> saveAll(Iterable<S> entities)
Parameters: Entities, keeping note that they must not be null nor must it contain null.
Return Type: the saved entities; will never be null. The returned Iterable will have the same size as the Iterable passed as an argument.
Exception Thrown: It throws IllegalArgumentException in case the given entities or one of its entities is null.
Method 2: getById(): Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is implemented this is very likely to always return an instance and throw an EntityNotFoundException on first access. Some of them will reject invalid identifiers immediately.
Syntax: 
T getById(ID id)
Parameters: id – must not be null.
Return Type: a reference to the entity with the given identifier.
Method 3: flush(): Flushes all pending changes to the database.
Syntax:
void flush()
Method 4: saveAndFlush(): Saves an entity and flushes changes instantly.
Syntax:
<S extends T> S saveAndFlush(S entity)
Parameters: The entity to be saved. Must not be null.
Return Type: The saved entity
Method 5: deleteAllInBatch(): Deletes the given entities in a batch which means it will create a single query. This kind of operation leaves JPAs first-level cache and the database out of sync. Consider flushing the EntityManager before calling this method.
Syntax:
 void deleteAllInBatch(Iterable<T> entities)
Parameters: The entities to be deleted, must not be null.
Implementation: Let us consider a Spring Boot application that manages a Department entity with JpaRepository. The data is saved in the H2 database. We use a RESTful controller.
Step 1: Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. 
Step 2: Add the following dependency
Spring Web
H2 Database
Lombok
Spring Data JPA
Example: Here is the complete code for the pom.xml file.
XML
<?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.5</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>com.amiya</groupId>    <artifactId>Spring-Boot-Demo-Project</artifactId>    <version>1.0.0-SNAPSHOT</version>    <name>Spring-Boot-Demo-Project</name>    <description>Demo project for Spring Boot</description>    <properties>        <java.version>11</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>          <dependency>            <groupId>com.h2database</groupId>            <artifactId>h2</artifactId>            <scope>runtime</scope>        </dependency>          <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-devtools</artifactId>            <scope>runtime</scope>            <optional>true</optional>        </dependency>          <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>          <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>          <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <optional>true</optional>        </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>
Step 3: Create 4 packages as listed below and create some classes and interfaces inside these packages as seen in the below image
entity
repository
service
controller
Note:
Green Rounded Icon ‘I’ Buttons are Interface
Blue Rounded Icon ‘C’ Buttons are Classes
Step 4: Inside the entity package
Create a simple POJO class inside the Department.java file. 
Java
// Java Program to Demonstrate Department File  // Importing package module to this code fragment package com.amiya.springbootdemoproject.entity;  import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor;  // Importing required classes import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;  @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder  // Class  public class Department {      @Id    @GeneratedValue(strategy = GenerationType.AUTO)        private Long departmentId;    private String departmentName;    private String departmentAddress;    private String departmentCode;}
Step 5: Inside the repository package
Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the JpaRepository as we have discussed above. 
Example:
Java
// Java Program to Illustrate DepartmentRepository File  // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.repository;  import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository;  // Annotation@Repository  // Interfacepublic interface DepartmentRepository    extends JpaRepository<Department, Long> {}
Step 6: Inside the service package
Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. 
Example 1-A:
Java
// Java Program to Demonstrate DepartmentService File  // Importing required package to code fragmentpackage com.amiya.springbootdemoproject.service;  import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List;  // Interfacepublic interface DepartmentService {      // Save operation    Department saveDepartment(Department department);      // Read operation    List<Department> fetchDepartmentList();      // Update operation    Department updateDepartment(Department department,                                Long departmentId);      // Delete operation    void deleteDepartmentById(Long departmentId);}
Example 1-B:
Java
// Java Program to Illustrate DepartmentServiceImpl File  // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.service;  import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;  // Annotation@Service  // Classpublic class DepartmentServiceImpl    implements DepartmentService {      @Autowired    private DepartmentRepository departmentRepository;      // Save operation    @Override    public Department saveDepartment(Department department)    {        return departmentRepository.save(department);    }      // Read operation    @Override public List<Department> fetchDepartmentList()    {        return (List<Department>)            departmentRepository.findAll();    }      // Update operation    @Override    public Department    updateDepartment(Department department,                     Long departmentId)    {        Department depDB            = departmentRepository.findById(departmentId)                  .get();          if (Objects.nonNull(department.getDepartmentName())            && !"".equalsIgnoreCase(                department.getDepartmentName())) {            depDB.setDepartmentName(                department.getDepartmentName());        }          if (Objects.nonNull(                department.getDepartmentAddress())            && !"".equalsIgnoreCase(                department.getDepartmentAddress())) {            depDB.setDepartmentAddress(                department.getDepartmentAddress());        }          if (Objects.nonNull(department.getDepartmentCode())            && !"".equalsIgnoreCase(                department.getDepartmentCode())) {            depDB.setDepartmentCode(                department.getDepartmentCode());        }          return departmentRepository.save(depDB);    }      // Delete operation    @Override    public void deleteDepartmentById(Long departmentId)    {        departmentRepository.deleteById(departmentId);    }}
Step 7: Inside the controller package
Inside the package create one class named as DepartmentController. 
Java
// Java Program to Demonstrate DepartmentController File  // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.controller;  import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;  // Annotation@RestController  // Classpublic class DepartmentController {      @Autowired private DepartmentService departmentService;      // Save operation    @PostMapping("/departments")    public Department saveDepartment(        @Valid @RequestBody Department department)    {        return departmentService.saveDepartment(department);    }      // Read operation    @GetMapping("/departments")    public List<Department> fetchDepartmentList()    {        return departmentService.fetchDepartmentList();    }      // Update operation    @PutMapping("/departments/{id}")    public Department    updateDepartment(@RequestBody Department department,                     @PathVariable("id") Long departmentId)    {        return departmentService.updateDepartment(            department, departmentId);    }      // Delete operation    @DeleteMapping("/departments/{id}")    public String deleteDepartmentById(@PathVariable("id")                                       Long departmentId)    {        departmentService.deleteDepartmentById(            departmentId);          return "Deleted Successfully";    }}
Step 8: Below is the code for the application.properties file
server.port = 8082

# H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database.
Endpoint 1: POST – http://localhost:8082/departments/
Endpoint 2: GET – http://localhost:8082/departments/
Endpoint 3: PUT – http://localhost:8082/departments/1
Endpoint 4: DELETE – http://localhost:8082/departments/1
H2 Database is a follows:
Java-Spring-Boot
Java
MongoDB
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Mongoose | findByIdAndUpdate() Function
Upload and Retrieve Image on MongoDB using Mongoose
Mongoose Populate() Method
Mongoose find() Function
MongoDB - db.collection.Find() Method