Spring JPA truncate table

Feb 15, 2022

If you want to truncate a table, which means that there is no redolog generated and therefor there is no rollback function to restore.

public interface MyTableRepository extends JpaRepository<MyTable, Long> {
    //....

    @Modifying
    @Query(
            value = "truncate table myTable",
            nativeQuery = true
    )
    void truncateMyTable();
}

If we look at the deleteAll function from SimpleJpaRepository we'll see the find call for all elements in the table and the delete statement in the foreach loop

//...

@Transactional
public void deleteAll() {

    for (T element : findAll()) {
        delete(element);
    }
}

So if you want to delete all entries in a table, you can use the deleteAllInBatch method.

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.