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.
I want to make sure that my query gets canceled after a certain time. Is there a way to define a timeout for queries?
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.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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
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 as a paperback, ebook or PDF.