How to set the timeout period on a JPA EntityManager query

Yes, there javax.persistence.query.timeout. According JPA 2.0 specification support for this query hint is optional:

Portable applications should not rely on this hint. Depending on the persistence provider and database in use, the hint may or may not be observed.

Default value (in milliseconds) can be set to persistence.xml for all queries:

<property name="javax.persistence.query.timeout" value="1000"/>

Same property can be also given when creating EntityManagerFactory via Persistence.createEntityManagerFactory.

It can also be overridden/set per query:

query.setHint("javax.persistence.query.timeout", 2000);

Same functionality can be obtained via attribute hints in NamedQuery.


There are two ways you can set up the query timeout period with Hibernate.

The Hibernate-specific way

If you are bootstrapping Hibernate natively or if you are unwrapping the JPA java.persistence.Query to its org.hibernate.query.Query equivalent, then you can just use the setTimeout method:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "where lower(p.title) like lower(:titlePattern)", Post.class)
.setParameter("titlePattern", "%Hibernate%")
.unwrap(org.hibernate.query.Query.class)
.setTimeout(1)
.getResultList();

Notice that the setTimeout method takes an int argument which specifies the timeout value in seconds.

The JPA query hint way

You can also use a JPA query hint, as illustrated in the following example:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "where lower(p.title) like lower(:titlePattern)", Post.class)
.setParameter("titlePattern", "%Hibernate%")
.setHint("javax.persistence.query.timeout", 50)
.getResultList();

Notice that the javax.persistence.query.timeout query hint takes the timeout value in milliseconds.

The Hibernate query hint way

You can also use the org.hibernate.timeout query hint:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "where lower(p.title) like lower(:titlePattern)", Post.class)
.setParameter("titlePattern", "%Hibernate%")
.setHint("org.hibernate.timeout", 1)
.getResultList();

Notice that the org.hibernate.timeout query hint takes the timeout value in seconds.