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.
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.
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.
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.