database - Spring boot Oracle JPA 设置 QueryTimeout

标签 database spring-boot spring-data-jpa timeout

我正在使用带有 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 be public for it to work properly

关于database - Spring boot Oracle JPA 设置 QueryTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58007112/

相关文章:

php - 如何使用group by得到多个结果集?在多列上分组

C#数据库连接保存在DLL中调用

database - 保留空数据库单元格的最佳方法是什么?

java - OPC UA调用Acknowlagement方法并在java中获取Bad_EventIdUnkown

java - 测试 Spring Boot REST API

hibernate - Spring 数据 JPA : return empty List instead of null

mongodb - 广泛的过滤

java - 在 Spring Boot 中从生成 PDF 内容类型内容的外部 Rest API 中提取响应字节的正确方法是什么?

java - JPA持久化 CrudRepository.save() 语法错误

java - Spring JPA 存储库无法捕获 EntityNotFoundException