java - JPA 查询超时参数被忽略,但 @Transaction 注释有效

标签 java spring jpa timeout jpa-2.0

我希望我的 Spring Boot 应用程序对 Postgres 数据库进行的 JPA 查询在 5 秒后超时。

我创建了这个 20 秒的查询来测试超时:

@Query(value = "select count(*) from pg_sleep(20)", nativeQuery = true)
int slowQuery();

我在 application.config 中设置了以下属性:

spring.jpa.properties.javax.persistence.query.timeout=3000
javax.persistence.query.timeout=5000

但查询在3s或5s后并没有超时(仍然需要20s才能执行)。

奇怪的是,如果我用 @Transactional(timeout = 10) 注释 slowQuery,它会在 10 秒左右后超时。

我不希望对每个查询都进行注释。我正在使用 JPA 2.0 和 Tomcat 连接池。

仅仅通过在应用程序属性文件中设置它们来使超时工作需要什么魔法?

最佳答案

要使超时通用,在您的 JpaConfiguration 中,当您声明 PlatformTransactionManager Bean 时,您可以设置事务的默认超时:

@Bean
public PlatformTransactionManager transactionManager() throws Exception {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory().getObject());
    txManager.setDataSource(this.dataSource);
    txManager.setDefaultTimeout(10); //Put 10 seconds timeout
    return txManager;
}

PlatformTransactionManager 继承了包含该方法的 AbstractPlatformTransactionManager:

    /**
     * Specify the default timeout that this transaction manager should apply
     * if there is no timeout specified at the transaction level, in seconds.
     * <p>Default is the underlying transaction infrastructure's default timeout,
     * e.g. typically 30 seconds in case of a JTA provider, indicated by the
     * {@code TransactionDefinition.TIMEOUT_DEFAULT} value.
     * @see org.springframework.transaction.TransactionDefinition#TIMEOUT_DEFAULT
     */
    public final void setDefaultTimeout(int defaultTimeout) {
        if (defaultTimeout < TransactionDefinition.TIMEOUT_DEFAULT) {
            throw new InvalidTimeoutException("Invalid default timeout", defaultTimeout);
        }
        this.defaultTimeout = defaultTimeout;
    }

关于java - JPA 查询超时参数被忽略,但 @Transaction 注释有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827071/

相关文章:

java - LRU缓存的并发版本

java - 调整 BufferedImages 的大小并将其存储到 JPG 图像黑色背景的文件结果中

java - 使用MultiPart上传图片

spring - 在 Spring 项目中使用 DataSource en sessionFactory 的 Hibernate 注释

java - 如果多个线程调用CountDownLatch的await()方法会发生什么?

java - 在 Android 中以本地化格式从字符串中单独显示日期和时间

java - 自动增量字段不返回值(非主键) - Spring boot JPA

java - 另一个支持 ejbql 连接的工具,如 Ireport (JasperReport)

java - JPA实体未映射异常

java - 如何在 netbeans 中创建 package-info.java 文件?