【问题标题】:Can't truncate PostgreSQL tables with JPA无法使用 JPA 截断 PostgreSQL 表
【发布时间】: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


【解决方案1】:

如果你的表之间有关系,你将无法截断表,因为是数据完整性违规异常,如果你使用数据库 H2,你可以做一些技巧:

SET REFERENTIAL_INTEGRITY FALSE;

TRUNCATE TABLE tbtable;

SET REFERENTIAL_INTEGRITY TRUE;

.sql

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 2013-04-02
    • 2011-09-13
    • 2018-06-06
    • 1970-01-01
    相关资源
    最近更新 更多