我正在使用带有 Ojdbc8 18.3.0.0.0 的 Spring Boot 使用 Hikari 数据源和 JPA,所有查询都可以正常工作。 但是现在我需要为所有数据库查询设置查询超时 我尝试了很多方法:
javax.persistence.query.timeout=1000
spring.transaction.default-timeout=1
spring.jdbc.template.query-timeout=1
spring.jpa.properties.hibernate.c3p0.timeout=1
spring.jpa.properties.javax.persistence.query.timeout=1
配置类:
@Configuration
public class JPAQueryTimeout {
@Value("${spring.jpa.properties.javax.persistence.query.timeout}")
private int queryTimeout;
@Bean
public PlatformTransactionManager transactionManager() throws Exception {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setDefaultTimeout(queryTimeout); //Put 1 seconds timeout
return txManager;
}
}
查询:
List<Integer> llll = manager.createNativeQuery("select test_sleep(5) from dual")
.setHint("javax.persistence.query.timeout", 1).getResultList();
数据库任务在返回值之前需要 5 秒,但在所有情况下,都不会发生错误。
谁能告诉我如何设置查询超时?
最佳答案
您可以尝试使用最简单的解决方案,即使用 @Transactional
中的 timeout
值;
@Transactional(timeout = 1) // in seconds (so that is 1 second timeout)
public Foo runQuery(String id) {
String result = repo.findById(id);
// other logic
}
Be aware that the method annotated with
@Transactional
must bepublic
for it to work properly
关于database - Spring boot Oracle JPA 设置 QueryTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58007112/