春季启动Oracle JPA设置QueryTimeout

时间:2019-09-19 08:45:29

标签: oracle spring-boot spring-data-jpa ojdbc

我正在将Spring Boot与Ojdbc8 18.3.0.0.0一起使用 使用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秒钟,但在所有情况下都不会发生错误。

谁能告诉我如何设置查询超时?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用最简单的解决方案,即使用timeout中的@Transactional值;

@Transactional(timeout = 1) // in seconds (so that is 1 second timeout)
public Foo runQuery(String id) {
    String result = repo.findById(id);
    // other logic
}
  

请注意,用@Transactional注释的方法必须为public,才能正常工作