JPA查询超时参数被忽略,但@Transaction注释有效 [英] JPA query timeout parameters ignored but @Transaction annotation works

查看:606
本文介绍了JPA查询超时参数被忽略,但@Transaction注释有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want JPA queries made by my Spring Boot application to a Postgres database to timeout after 5 seconds.

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

I have created this 20 seconds query to test timeouts:

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

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

I've set the following properties in application.config:

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

但是查询不会在3s或5s后超时(仍然需要20s来执行).

But the query does not timeout after 3s or 5s (it still takes 20s to execute).

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

Strangely, if I annotate slowQuery with @Transactional(timeout = 10), it times out after 10s or so.

我不希望为每个查询添加注释.我正在使用JPA 2.0和Tomcat连接池.

I would prefer not to annotate every query. I'm using JPA 2.0 and the Tomcat connection pool.

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

What magic is required to make the timeout work just by setting them in application properties file?

推荐答案

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

To make the timeout generic, in your JpaConfiguration, when you declare the PlatformTransactionManager Bean, you can set the default timeout of the transactions:

@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:

PlatformTransactionManager inherits AbstractPlatformTransactionManager which contains that method:

    /**
     * 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;
    }

这篇关于JPA查询超时参数被忽略,但@Transaction注释有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆