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);
}
}
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());
}
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();