Engineering With Java

Engineering With Java

Spring Data JPA: deleteAllInBatch*() Methods Explained!

Internal code exploration with sample dataset, examples, and more.

Suraj Mishra's avatar
Suraj Mishra
Mar 06, 2025
∙ Paid

Introduction

  • Spring Data JPA provides a lot of handy features to interact with databases for all kinds of operations.

  • One of the much-used operations is the deletion of the records. But deleting large numbers of records one by one is not resource efficient, hence doing it them in batches makes much sense.

  • Spring Data JPA provides helper methods that allow us to delete records in batches. In this article, we will deep dive into them, we will explore the internal code of these methods, and write logic along with the execution.


Consider becoming a free or paid subscriber and support the work :)

Still not convinced? Check out the details of the past work


Sample Table/Model

  • First of all, let's create a sample table Campaign with some mock data.

Inserting Sample Data

  • Now let's insert 1M records to the Campaign table. The below script (plpgsql) does the job.

  • Now our table contains 1M records that we can delete from Spring Data JPA.

postgres=# select count(*) from campaign;
  count
---------
 1000000
(1 row)

JpaRepository

  • JpaRepository is one of the common repositories that we extend when we define our repository interface for managing our entities.

  • JpaRepository provides 3 helper methods that can delete records in batches:
    1. deleteAllInBatch()
    2. deleteAllInBatch(Iterable<T> entities)
    3. deleteAllByIdInBatch(Iterable<ID> ids)

  • Since JpaRepository is an interface, its implementation exists in the SimpleJpaRepository class.

Now let's deep dive into these methods and write some code along with execution.

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Suraj Mishra · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture