How to set a default query timeout with JPA and Hibernate?

前端 未结 5 1496
南方客
南方客 2020-11-29 10:10

I am doing some big queries on my database with Hibernate and I sometimes hit timeouts. I would like to avoid setting the timeout manually on every Query or

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 11:06

    Yes, you can do that.

    As I explained in this article, all you need to do is to pass the JPA query hint as a global property:

    
    

    Now, when executing a JPQL query that will timeout after 1 second:

    List posts = entityManager
    .createQuery(
        "select p " +
        "from Post p " +
        "where function('1 >= ALL ( SELECT 1 FROM pg_locks, pg_sleep(2) ) --',) is ''", Post.class)
    .getResultList();
    

    Hibernate will throw a query timeout exception:

    SELECT p.id AS id1_0_,
           p.title AS title2_0_
    FROM post p
    WHERE 1 >= ALL (
        SELECT 1
        FROM pg_locks, pg_sleep(2)
    ) --()=''
    
    -- SQL Error: 0, SQLState: 57014
    -- ERROR: canceling statement due to user request
    

    For more details about setting a timeout interval for Hibernate queries, check out this article.

提交回复
热议问题