【发布时间】:2019-05-19 10:49:20
【问题描述】:
我正在尝试使用 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 万条记录),但耗时太长。我会感谢任何提示。
【问题讨论】:
-
尝试使用@Transactional at truncate in repository interface
-
直接在数据库上执行命令是否有效?
-
当询问异常时,请发布完整且准确的异常堆栈跟踪。您似乎在创建 bean 时尝试使用您的存储库,而不是等待应用程序初始化后再执行。
-
我设法解决了这个问题。我不确定我做了什么,但是我忘记了我在其中调用
deleteRepository()的方法是用@Transactional注释的,所以我删除了该注释。另外,我将查询更改为truncate table my_table cascade。现在删除基本上是即时的。
标签: spring postgresql hibernate jpa spring-data-jpa