Tip: Efficient Data Deletion Strategies in JPA for Large Datasets (beware of deleteAll in JPA)

Note for me: Please remember to use the search function to find this note in the blog when needed.

If you need to delete all data from a JPA table, avoid using the deleteAll method as it will iterate through all elements and delete them one by one. This can be time-consuming and inefficient, especially when dealing with a large amount of records. I

public void deleteAll() {
Iterator var1 = this.findAll().iterator();

while(var1.hasNext()) {
T element = var1.next();
this.delete(element);
}
}

Source: https://github.com/sbj156/-/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java#L196

Instead, use the deleteAllInBatch method with the typical delete from statement.

@Transactional
public void deleteAllInBatch() {
this.em.createQuery(this.getDeleteAllQueryString()).executeUpdate();
}
private String getDeleteAllQueryString() {
return QueryUtils.getQueryString("delete from %s x", this.entityInformation.getEntityName());
}

Source: https://github.com/sbj156/-/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java#L208

If that is not an option, consider using truncate to delete all data from the table.

 @Modifying
@Transactional
@Query(value = "TRUNCATE TABLE my_entity", nativeQuery = true)
void truncateTable();

Deja un comentario