Hibernate Tips: How to define a query timeout


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

I want to make sure that my query gets canceled after a certain time. Is there a way to define a timeout for queries?

Solution:

JPA and Hibernate support the javax.persistence.query.timeout query hint to define a query timeout in milliseconds. Hibernate uses it to call the setTimeout method on the JDBC Statement and doesn’t handle the timeout itself. It, therefore, depends on the JDBC driver and the database capabilities, if the query hint has any effect.

The following 2 code snippets show you how to provide the query timeout hint to a Query and the EntityManager.find method.

List<Author> authors = em.createQuery("SELECT a FROM Author a")
	.setHint("javax.persistence.query.timeout", 1000)
	.getResultList();
HashMap<String, Object> hints = new HashMap<>();
hints.put("javax.persistence.query.timeout", 1000);

em.find(Author.class, 1L, hints);

Learn more:

The query timeout is just one of multiple query hints supported by JPA and Hibernate. I explained more of them in 11 JPA and Hibernate query hints every developer should know.

Hibernate Tips Book

Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!

3 Comments

    1. Avatar photo Thorben Janssen says:

      You are, of course, right!

  1. Avatar photo Sanjeev Dhiman says:

    Short and sweet 🙂 Good tip

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.