无法使用JPA截断PostgreSQL表

时间:2019-05-19 10:49:20

标签: spring postgresql hibernate jpa spring-data-jpa

我正在尝试使用Spring Data JPA快速删除多个表中的所有数据。据我了解,最快的方法是截断表。

我的代码如下:

@Service
public class DatabaseService {

    ... autowiring ...

    @Transactional
    public void deleteRepository(){
        repository.truncate();
    }
}
@Repository
public interface repository extends JpaRepository<Trip, Long> {

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

但是,当我调用deleteRepository()方法时,会出现以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'databasePopulatorJob': Invocation of init method failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: java.sql.SQLException: Connection is closed
...

我正在使用最新的PostgreSQL数据库和JDBC驱动程序版本42.2.5。

我还尝试了其他方法来删除数据,例如DELETE FROM my_table(my_table包含大约200万条记录),但是花费的时间太长了。我会推荐任何提示。

1 个答案:

答案 0 :(得分:0)

如果表之间有关系,则将无法截断表,因为是数据完整性违规异常,如果您正在使用数据库H2,请执行以下操作:

SET REFERENTIAL_INTEGRITY FALSE;

TRUNCATE TABLE tbtable;

SET REFERENTIAL_INTEGRITY TRUE;

.sql

相关问题