Spring Data JPA - save(), findById(), findAll(), deleteById() Example

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

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.
 
Read more about Spring Data at Spring Data JPA - Getting Started

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 the save()findById()findAll(), and deleteById() methods of the JpaRepository (Spring Data JPA) interface.

Spring Data JPA - save(), findById(), findAll(), deleteById() Example

Let's create a new Spring Boot project to demonstrate the usage of 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.

2. Maven Dependencies

Add the following maven dependencies to your Spring Boot project:
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>

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

Product Entity

Let's first create a Product entity that we are going to save/get/update/delete product records into the database table.
package net.javaguides.springdatajpacourse.entity;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.util.Date;

@Entity
@Table(name="products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "sku")
    private String sku;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "price")
    private BigDecimal price;

    @Column(name = "image_url")
    private String imageUrl;

    @Column(name = "active")
    private boolean active;

    @Column(name = "date_created")
    @CreationTimestamp
    private Date dateCreated;

    @Column(name = "last_updated")
    @UpdateTimestamp
    private Date lastUpdated;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }

    public Date getLastUpdated() {
        return lastUpdated;
    }

    public void setLastUpdated(Date lastUpdated) {
        this.lastUpdated = lastUpdated;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", sku='" + sku + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                ", imageUrl='" + imageUrl + '\'' +
                ", active=" + active +
                ", dateCreated=" + dateCreated +
                ", lastUpdated=" + lastUpdated +
                '}';
    }
}

ProductRepository

Let's create ProductRepository which extends the JpaRepository interface. As we know that JpaRepository interface provides the save() method so our ProductRepository interface should extend to the JpaRepository interface to get all its methods:

import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {

}

Configure MySQL and Hibernate Properties

Let's use the MySQL database to store and retrieve the data in this example and we gonna use Hibernate properties to create and drop tables.

Open the application.properties file and add the following configuration to it:

spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect

spring.jpa.hibernate.ddl-auto = create-drop

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Make sure that you will create ecommerce database before running the Spring boot application.
Also, change the MySQL username and password as per your MySQL installation on your machine.

Testing save() Method

In order to test the save() method, we gonna use CommandLineRunner.run() method to execute the testing code while the Spring boot application startup:
import net.javaguides.springdatajpacourse.entity.Product;
import net.javaguides.springdatajpacourse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.math.BigDecimal;
import java.util.Date;

@SpringBootApplication
public class SpringDataJpaCourseApplication implements CommandLineRunner{

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringDataJpaCourseApplication.class, args);
	}

	@Autowired
	private ProductRepository productRepository;

	@Override
	public void run(String... args) throws Exception {
		Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setDateCreated(new Date());
        product.setLastUpdated(new Date());
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");

        // save product
        productRepository.save(product);
	}
}
After finished Spring boot application runs, you can able to see Hibernate generate an INSERT SQL statement in a console:

Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)

Testing findById() Method

In order to test the findById() method, we gonna use CommandLineRunner.run() method to execute the testing code while the Spring boot application startup: 
import net.javaguides.springdatajpacourse.entity.Product;
import net.javaguides.springdatajpacourse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@SpringBootApplication
public class SpringDataJpaCourseApplication implements CommandLineRunner{

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringDataJpaCourseApplication.class, args);
	}

	@Autowired
	private ProductRepository productRepository;

	@Override
	public void run(String... args) throws Exception {
		Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setDateCreated(new Date());
        product.setLastUpdated(new Date());
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");

        // save the product
        productRepository.save(product);

        // get product by id
        Product savedProduct = productRepository.findById(product.getId()).get();
        System.out.println(savedProduct);
	}
}

After finishing the Spring boot application, you can able to see Hibernate-generated SQL statements in a console:
Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        product0_.id as id1_0_0_,
        product0_.active as active2_0_0_,
        product0_.date_created as date_cre3_0_0_,
        product0_.description as descript4_0_0_,
        product0_.image_url as image_ur5_0_0_,
        product0_.last_updated as last_upd6_0_0_,
        product0_.name as name7_0_0_,
        product0_.price as price8_0_0_,
        product0_.sku as sku9_0_0_ 
    from
        products product0_ 
    where
        product0_.id=?
INSERT SQL statement to save the entity:
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
SELECT SQL statement get entity by id:

    select
        product0_.id as id1_0_0_,
        product0_.active as active2_0_0_,
        product0_.date_created as date_cre3_0_0_,
        product0_.description as descript4_0_0_,
        product0_.image_url as image_ur5_0_0_,
        product0_.last_updated as last_upd6_0_0_,
        product0_.name as name7_0_0_,
        product0_.price as price8_0_0_,
        product0_.sku as sku9_0_0_ 
    from
        products product0_ 
    where
        product0_.id=?

Testing findAll() Method

In order to test the findAll() method, we gonna use CommandLineRunner.run() method to execute the testing code while the Spring boot application startup: 
import net.javaguides.springdatajpacourse.entity.Product;
import net.javaguides.springdatajpacourse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@SpringBootApplication
public class SpringDataJpaCourseApplication implements CommandLineRunner{

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringDataJpaCourseApplication.class, args);
	}

	@Autowired
	private ProductRepository productRepository;

	@Override
	public void run(String... args) throws Exception {
		Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setDateCreated(new Date());
        product.setLastUpdated(new Date());
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");
        productRepository.save(product);

        Product product2 = new Product();
        product2.setName("product 2");
        product2.setDescription("product 2 desc");
        product2.setPrice(new BigDecimal(200));
        product2.setDateCreated(new Date());
        product2.setLastUpdated(new Date());
        product2.setSku("product 2 sku");
        product2.setActive(true);
        product2.setImageUrl("product2.png");
        productRepository.save(product2);

        // get or retrieve all products
        Iterable<Product> products = productRepository.findAll();
        products.forEach((p) -> {
            System.out.println(p.getName());
        });
	}
}

After finishing the Spring boot application, you can able to see Hibernate-generated SQL statements in a console:
Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        product0_.id as id1_0_,
        product0_.active as active2_0_,
        product0_.date_created as date_cre3_0_,
        product0_.description as descript4_0_,
        product0_.image_url as image_ur5_0_,
        product0_.last_updated as last_upd6_0_,
        product0_.name as name7_0_,
        product0_.price as price8_0_,
        product0_.sku as sku9_0_ 
    from
        products product0_
Two INSERT SQL statements to save the two entities:
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
SELECT SQL statement get all entities:
    select
        product0_.id as id1_0_,
        product0_.active as active2_0_,
        product0_.date_created as date_cre3_0_,
        product0_.description as descript4_0_,
        product0_.image_url as image_ur5_0_,
        product0_.last_updated as last_upd6_0_,
        product0_.name as name7_0_,
        product0_.price as price8_0_,
        product0_.sku as sku9_0_ 
    from
        products product0_

Testing deleteById() Method

In order to test the deleteById() method, we gonna use CommandLineRunner.run() method to execute the testing code while the Spring boot application startup: 
import net.javaguides.springdatajpacourse.entity.Product;
import net.javaguides.springdatajpacourse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.math.BigDecimal;
import java.util.Date;

@SpringBootApplication
public class SpringDataJpaCourseApplication implements CommandLineRunner{

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringDataJpaCourseApplication.class, args);
	}

	@Autowired
	private ProductRepository productRepository;

	@Override
	public void run(String... args) throws Exception {
		Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setDateCreated(new Date());
        product.setLastUpdated(new Date());
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");
        productRepository.save(product);

        // DELETE PRODUCT BY ID
        productRepository.deleteById(product.getId());
	}
}

After finishing the Spring boot application, you can able to see Hibernate-generated SQL statements in a console. Note that deleteById() method first get an entity by id from that database table and delete using entity id (primary key) hence you can see select SQL statement in a console.
Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        product0_.id as id1_0_0_,
        product0_.active as active2_0_0_,
        product0_.date_created as date_cre3_0_0_,
        product0_.description as descript4_0_0_,
        product0_.image_url as image_ur5_0_0_,
        product0_.last_updated as last_upd6_0_0_,
        product0_.name as name7_0_0_,
        product0_.price as price8_0_0_,
        product0_.sku as sku9_0_0_ 
    from
        products product0_ 
    where
        product0_.id=?
Hibernate: 
    delete 
    from
        products 
    where
        id=?
INSERT SQL statements to save an entity:
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
DELETE SQL statement to delete an entity by id:
    delete 
    from
        products 
    where
        id=?

Conclusion

In this tutorial, we learned how to use the save()findById()findAll(), and deleteById() methods of JpaRepository (Spring Data JPA) with Spring Boot.

Comments