Is it possible to use "TRUNCATE" in Spring Data JPA using JpaRepository? Or a more effective method than the standard deleteAll()?

Example, in your service interface:

public interface MyTableInterface {
    //...

    void truncateMyTable();
}

In your service implementation (with @Autowired myTableRepository):

public class MyTableImpl implements MyTableService {

    // other methods, @Autowiring, etc

    @Override
    @Transactional
    public void truncateMyTable() {
        myTableRepository.truncateMyTable();
    }
}

In your repository;

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

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

EDIT: Also notice the @Transactional on service implemntation layer, instead of placing it on DAO/Repository layer


deleteAll is fetching all entities and then removes one by one:

// Code from SimpleJpaRepository

@Transactional
public void deleteAll() {

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

I would suggest that you create your own delete method in the repo like:

@Modifying
@Transactional
@Query("delete from MyEntity m")
void deleteAllWithQuery();

This will create only one SQL DELETE statement.