Spring Boot - save(), findById(), findAll(), deleteById() Tutorial

In this tutorial, we will learn how to use 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

Spring Data JPA is not a JPA provider. It is a library/framework that adds an extra layer of abstraction on the top of our JPA provider (like Hibernate).

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.

Spring boot save(), findById(), findAll(), deleteById() Example

The following Spring Boot application manages an Employee entity with JpaRepository. The data is saved in the H2 database. The application is a console program.

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.

2. Pom Dependencies - pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


         <relativePath /> <!-- lookup parent from repository -->



The spring-boot-starter-data-jpa is a starter for using Spring Data JPA with Hibernate.

3. resources/application.properties

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

package net.guides.springboot.jparepository.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@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;
    @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;

    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
    + "]";

5. Service Layer


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);


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;

public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeRepository employeeRepository;

    public Optional < Employee > findById(Long id) {
        return employeeRepository.findById(id);

    public void save(Employee employee) {

    public List < Employee > findAll() {
        return employeeRepository.findAll();

    public void delete(long id) {

6. JPA Repository - EmployeeRepository.java

The EmployeeRepository extends from the JpaRepository. It provides the type of the entity and of 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;

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;

public class MyRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);

    private EmployeeService emplyeeService;
    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;

        long id2 = 5L;
        Optional < Employee > optional = emplyeeService.findById(id2);

        if (optional.isPresent()) {
        } 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

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;

public class Application {

    public static void main(String[] args) {
         SpringApplication.run(Application.class, args);

9. Output

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course


Post a Comment