In this tutorial, we will learn how to use the save(), findById(), findAll(), and deleteById() methods of JpaRepository (Spring Data JPA) with Spring Boot.
As we know that Spring is a popular Java application framework. Spring Boot is an effort to create stand-alone, production-grade Spring-based applications with minimal effort.
Spring Data JPA Overview
We can use Spring Data JPA to reduce the amount of boilerplate code required to implement the data access object (DAO) layer.Spring Data JPA is not a JPA provider. It is a library/framework that adds an extra layer of abstraction on top of our JPA provider (like Hibernate). Spring Data JPA uses Hibernate as a default JPA provider.
JpaRepository Interface
JpaRepository is JPA 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.
Well, Spring Data JPA provides SimpleJpaRepository class that implements the JpaRepository interface and its methods. It means the SimpleJpaRepository class provides an implementation of save(), findById(), findAll(), and deleteById() methods of JpaRepository (Spring Data JPA) with Spring Boot.
Well, Spring Data JPA provides SimpleJpaRepository class that implements the JpaRepository interface and its methods. It means the SimpleJpaRepository class provides an implementation of save(), findById(), findAll(), and deleteById() methods of JpaRepository (Spring Data JPA) with Spring Boot.
Spring boot save(), findById(), findAll(), deleteById() Example
Let's create a new Spring Boot project to demonstrate the usage of the save(), findById(), findAll(), and deleteById() methods of the JpaRepository (Spring Data JPA) interface.
1. Create a Spring Boot Application
There are many ways to create a Spring Boot application. You can refer below articles to create a Spring Boot application.>> Create Spring Boot Project With Spring Initializer
>> Create Spring Boot Project in Spring Tool Suite [STS]
2. Maven Dependencies - pom.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.guides.springboot2</groupId>
<artifactId>springboot-jparepository-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.4</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The spring-boot-starter-data-jpa is a starter for using Spring Data JPA with Hibernate.
3. resources/application.properties
spring.main.banner-mode=off
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n
The application.properties is the main Spring Boot configuration file.
With the spring.main.banner-mode the property we turn off the Spring banner. The logging.pattern.consoleDefines the log pattern for the console.
4. JPA Entity - Employee.java
Let's create an Employee entity class and add the following content to it:
package net.guides.springboot.jparepository.model;
import jakarta.persistence.*;
@Entity
@Table(name = "employees")
public class Employee {
private long id;
private String firstName;
private String lastName;
private String emailId;
public Employee() {
}
public Employee(String firstName, String lastName, String emailId) {
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "email_address", nullable = false)
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
+ "]";
}
}
5. Service Layer
EmployeeService.java
package net.guides.springboot.jparepository.service;
import java.util.List;
import java.util.Optional;
import net.guides.springboot.jparepository.model.Employee;
public interface EmployeeService {
List < Employee > findAll();
void save(Employee employee);
Optional < Employee > findById(Long id);
void delete(long id);
}
EmployeeServiceImpl.java
package net.guides.springboot.jparepository.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.guides.springboot.jparepository.model.Employee;
import net.guides.springboot.jparepository.repository.EmployeeRepository;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public Optional < Employee > findById(Long id) {
return employeeRepository.findById(id);
}
@Override
public void save(Employee employee) {
employeeRepository.save(employee);
}
@Override
public List < Employee > findAll() {
return employeeRepository.findAll();
}
@Override
public void delete(long id) {
employeeRepository.deleteById(id);
}
}
This is an example implementation of an EmployeeService interface in Spring Boot that uses the methods findById(), save(), findAll(), and deleteById() of an EmployeeRepository interface to perform database operations on Employee objects.
The @Service annotation is used to indicate that this class is a service component in the Spring framework, and it will be managed by the Spring container. The EmployeeRepository object is injected into this class using the @Autowired annotation.
The findById() method takes a Long parameter id and returns an Optional object that contains the Employee object with the specified id if it exists in the database. If the object is not found, an empty Optional object is returned.
The save() method takes an Employee object as a parameter and saves it to the database using the save() method of the EmployeeRepository.
The findAll() method returns a list of all Employee objects in the database using the findAll() method of the EmployeeRepository.
The delete() method takes a long parameter id and deletes the Employee object with the specified id from the database using the deleteById() method of the EmployeeRepository.
Overall, this class provides an implementation of the EmployeeService interface that allows clients to perform CRUD operations on Employee objects in the database.
The @Service annotation is used to indicate that this class is a service component in the Spring framework, and it will be managed by the Spring container. The EmployeeRepository object is injected into this class using the @Autowired annotation.
The findById() method takes a Long parameter id and returns an Optional object that contains the Employee object with the specified id if it exists in the database. If the object is not found, an empty Optional object is returned.
The save() method takes an Employee object as a parameter and saves it to the database using the save() method of the EmployeeRepository.
The findAll() method returns a list of all Employee objects in the database using the findAll() method of the EmployeeRepository.
The delete() method takes a long parameter id and deletes the Employee object with the specified id from the database using the deleteById() method of the EmployeeRepository.
Overall, this class provides an implementation of the EmployeeService interface that allows clients to perform CRUD operations on Employee objects in the database.
6. JPA Repository - EmployeeRepository.java
The EmployeeRepository extends from the JpaRepository interface. It provides the type of entity and its primary key.package net.guides.springboot.jparepository.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.guides.springboot.jparepository.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
7. MyRunner.java
package net.guides.springboot.jparepository;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import net.guides.springboot.jparepository.model.Employee;
import net.guides.springboot.jparepository.service.EmployeeService;
@Component
public class MyRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);
@Autowired
private EmployeeService emplyeeService;
@Override
public void run(String...args) throws Exception {
emplyeeService.save(new Employee("Ramesh", "Fadatare", "ramesh@gmail.com"));
emplyeeService.save(new Employee("Tom", "Cruise", "tom@gmail.com"));
emplyeeService.save(new Employee("John", "Cena", "john@gmail.com"));
emplyeeService.save(new Employee("tony", "stark", "stark@gmail.com"));
long id1 = 1L;
emplyeeService.findById(id1).ifPresent(System.out::println);
long id2 = 5L;
Optional < Employee > optional = emplyeeService.findById(id2);
if (optional.isPresent()) {
System.out.println(optional.get());
} else {
System.out.printf("No employee found with id %d%n", id2);
}
// get list of employees
List < Employee > employees = emplyeeService.findAll();
employees.forEach(employee -> System.out.println(employee.toString()));
// delete employee by id
emplyeeService.delete(3L);
}
}
8. Running Spring Boot Application
The Application sets up the Spring Boot application. Let's run this Application class:package net.guides.springboot.jparepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Comments
Post a Comment
Leave Comment