Spring Boot CrudRepository Example Tutorial

SpringBoot CrudRepository example tutorial shows how to use CrudRepository to manage data in a Spring Boot application.

CrudRepository interface Overview

Spring Data Commons is part of the umbrella Spring Data project that provides shared infrastructure across the Spring Data projects. It contains technology-neutral repository interfaces as well as a metadata model for persisting Java classes.
 
Spring Data Commons project provides CrudRepository<T, ID extends Serializable> interface.

The CrudRepository repository provides basic CRUD operations, including count, delete, deleteById, save, saveAll, findById, and findAll.

Well, Spring Data JPA provides SimpleJpaRepository class that implements the CrudRepository interface and its methods. It means the SimpleJpaRepository class provides an implementation of the save()findById()findAll(), and deleteById() methods of the CrudRepository (Spring Data JPA) interface.

Spring Boot CrudRepository Example

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

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.

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-jprepository-example</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>springboot2-jpa-crud-example</name>
 <description>Demo project for Spring Boot</description>

 <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.

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.console Defines the log pattern for the console.

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;

@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
    + "]";
    }
 
}

JPA Repository - EmployeeRepository.java

The EmployeeRepository extends from the CrudRepository. It provides the type of the entity and of its primary key.
package net.guides.springboot.jparepository.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import net.guides.springboot.jparepository.model.Employee;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long>{

}
By extending the CrudRepository interface, this EmployeeRepository interface inherits all of its methods, which can be used to perform CRUD operations on Employee objects in the database. For example, 
The save() method can be used to save an Employee object to the database.
The findById() method can be used to retrieve an Employee object by its ID.
The findAll() method can be used to retrieve all Employee objects.
The deleteById() method can be used to delete an Employee object by its ID.

MyRunner.java

The MyRunner implements the CommandLineRunner interface and performs various database operations on Employee objects using the EmployeeRepository interface. This MyRunner class will be called whenever we start the Spring Boot application.
package net.guides.springboot.jparepository;

import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import net.guides.springboot.jparepository.model.Employee;
import net.guides.springboot.jparepository.repository.EmployeeRepository;

@Component
public class MyRunner implements CommandLineRunner {

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

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public void run(String...args) throws Exception {

        employeeRepository.save(new Employee("Ramesh", "Fadatare", "ramesh@gmail.com"));
        employeeRepository.save(new Employee("Tom", "Cruise", "tom@gmail.com"));
        employeeRepository.save(new Employee("John", "Cena", "john@gmail.com"));
        employeeRepository.save(new Employee("tony", "stark", "stark@gmail.com"));

        logger.info("# of employees: {}", employeeRepository.count());

        logger.info("All employees unsorted:");

        Iterable < Employee > employees = employeeRepository.findAll();
        Iterator < Employee > iterator = employees.iterator();
        while (iterator.hasNext()) {
            logger.info("{}", iterator.next().toString());
        }

        logger.info("------------------------");

        logger.info("Deleting employee with id 1");
        employeeRepository.deleteById(1 L);

        logger.info("# of employees: {}", employeeRepository.count());

        employeeRepository.existsById(2 L);
        employeeRepository.findById(2 L);
    }
}

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);
    }
}
Once you start the Spring boot application then it will call MyRunner class and executes its run() method.

Output

19-06-30 Sun 11:45:18.340 INFO  MyRunner # of employees: 4
19-06-30 Sun 11:45:18.340 INFO  MyRunner All employees unsorted:
19-06-30 Sun 11:45:18.385 INFO  MyRunner Employee [id=1, firstName=Ramesh, lastName=Fadatare, emailId=ramesh@gmail.com]
19-06-30 Sun 11:45:18.385 INFO  MyRunner Employee [id=2, firstName=Tom, lastName=Cruise, emailId=tom@gmail.com]
19-06-30 Sun 11:45:18.385 INFO  MyRunner Employee [id=3, firstName=John, lastName=Cena, emailId=john@gmail.com]
19-06-30 Sun 11:45:18.385 INFO  MyRunner Employee [id=4, firstName=tony, lastName=stark, emailId=stark@gmail.com]
19-06-30 Sun 11:45:18.385 INFO  MyRunner ------------------------
19-06-30 Sun 11:45:18.385 INFO  MyRunner Deleting employee with id 1
19-06-30 Sun 11:45:18.405 INFO  MyRunner # of employees: 3

Comments