java-JPA查询超时参数被忽略,但@Transaction注释有效
作者:互联网
我希望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;
}
标签:jpa,jpa-2-0,timeout,spring,java 来源: https://codeday.me/bug/20191024/1923854.html