Search code examples
spring-data-jpabatch-delete

Batch deletion for Spring data JPA


I have around 20k records to be deleted from Spring data JPA query , query is related to deleting all records before some particular date.

I am using below query

dao.deleteByCreationDateBefore(new Date());

I think this query hits database for each row deletion.

Please let me know is there any way I can use batch deletion here?

Regards


Solution

  • spting data doen't support batch operation.

    try to do it with simple delete if it's possible , like : it be very fast operation (faster than butch delete)

    delete from SOME_ENTITY/TABLE where CreationDate < new Date()/curentDate

    if your dao method delete record by record : But you can do it with hibernate/jpa in dao level , like (example from site with persist) from Hibernate/JPA Batch Insert and Batch Update Example:

        em.getTransaction().begin();
        for (int i = 0; i < 100; i++){
            Book book = new Book(i, "Hibernate/JPA Batch Insert Example: " + i);
            em.persist(book);
    
            if (i % batchSize == 0 && i > 0) {
                em.flush();
                em.clear();
            }
        }
        em.getTransaction().commit();
    

    for hibernate : and here is article How to batch INSERT and UPDATE statements with Hibernate , read about 'Configuring hibernate.jdbc.batch_size'. And Hibernate JDBC and Connection Properties options for hibernate for hibernate.jdbc.fetch_size and hibernate.jdbc.batch_size