Spring Data JPA deleteAll() Method Example

In this source code example, we will demonstrate how to use the deleteAll() method in Spring Data JPA to delete all the records from the database table.

The primary purpose of the deleteAll() method is to delete all entities managed by the repository. It's a bulk operation, which means it attempts to remove every single record in the corresponding table.

In this example, we will use the Product entity to save and delete to/from the MySQL database.

Maven Dependencies

First, you need to add the below 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>

Create Product Entity

Let's first create a Product entity that we are going to save and delete to/from the MySQL database:

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;

    // getter and setter methods

    @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:
import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.jpa.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/demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123

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 a demo database before running the Spring boot application.
Also, change the MySQL username and password as per your MySQL installation on your machine.

Testing deleteAll() Method

Let's write a JUnit test to test deleteAll() method:

import net.javaguides.springdatajpacourse.entity.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.annotation.Rollback;

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

@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest {

    @Autowired
    private ProductRepository productRepository;

    protected Product getProduct1(){
        Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");
        return product;
    }

    protected Product getProduct2(){
        Product product2 = new Product();
        product2.setName("product 2");
        product2.setDescription("product 2 desc");
        product2.setPrice(new BigDecimal(200));
        product2.setSku("product 2 sku");
        product2.setActive(true);
        product2.setImageUrl("product2.png");
        return product2;
    }

    @Rollback(value = false)
    @Test
    void testDeleteAllMethod(){
        Product product = getProduct1();

        Product product2 = getProduct2();

        productRepository.saveAll(List.of(product, product2));

        productRepository.deleteAll();
    }
}
We are using @DataJpaTest annotation to write a JUnit test for ProductRepository deleteAll() method.

@AutoConfigureTestDatabase annotation is to disable embedded in-memory database support and enable MySQL database support.

Output

Here is the output of the above JUnit test case we wrote for testing deleteAll() method:

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_
Hibernate: 
    delete 
    from
        products 
    where
        id=?
Hibernate: 
    delete 
    from
        products 
    where
        id=?

Note that Spring Data JPA (Hibernate) produces the SQL query to delete all the records from the database table.

 delete 
    from
        products 
    where
        id=?
Hibernate: 
    delete 
    from
        products 
    where
        id=?

Key Considerations:

Performance: Since this method deletes all records from a table, it can be a heavy operation, especially for large datasets. Use it judiciously and be aware of its potential performance implications.

Database Constraints: If other tables reference the records in the table you're trying to clear, you might run into referential integrity issues. Ensure you understand the relationships and constraints in your database.

Transactional Boundaries: Often, it's a good idea to run bulk operations like deleteAll() within a transaction to ensure database consistency. If an error occurs partway through the process, the transaction can be rolled back, preventing partial data deletions.

Backup: Given that this method removes all records, always ensure you have a recent backup of your data before using deleteAll().

Related Spring Data JPA Examples


Comments