问题
I would like to set a timeout on a javax.persistence.TypedQuery.
I've found this easy method :
TypedQuery<Foo> query = ... ;
query.setHint("javax.persistence.query.timeout", 1000);
query.getReturnList();
But it seems that does not work, it's just ignored.
From the PRO JPA 2 book:
"Unfortunately, setting a query timeout is not portable behavior. It may not be supported by all database platforms nor is it a requirement to be supported by all persistence providers. Therefore, applications that want to enable query timeouts must be prepared for three scenarios.
The first is that the property is silently ignored and has no effect.
The second is that the property is enabled and any select, update, or delete operation that runs longer than the specified timeout value is aborted, and a QueryTimeoutException is thrown. This exception may be handled and will not cause any active transaction to be marked for rollback.
The third scenario is that the property is enabled, but in doing so the database forces a transaction rollback when the timeout is exceeded. In this case, a PersistenceException will be thrown and the transaction marked for rollback. In general, if enabled the application should be written to handle the QueryTimeoutException, but should not fail if the timeout is exceeded and the exception is not thrown."
Does anyone knows any other method to specify a timeout on a TypedQuery?
Or how can I make this "hint" working?
Thanks
EDIT: Oracle 11.2.0.4.0 and PostgreSql 9.2.9 with JPA 2.1 / Hibernate
回答1:
I know its late to reply, but we faced similar problem Oracle 11g, JPA2.0 and this hint wasn't working.
Actually the problem was we were using it as @NamedQuery hint and were calling the function inside @transactional aspect. As @NamedQuery gets loaded and compiled at the time of context load this timeout was overridden by transaction timeout. You can find more info at http://javadeveloperz0ne.blogspot.in/2015/07/why-jpa-hints-on-namedquery-wont-work.html.
Solution would be fetching named query again and then applying timeout.
Query query = entityManager.createNamedQuery("NamedQueryName");
query.setHint("org.hibernate.timeout", "5");
query.getSingleResult();
Hope it helps!
回答2:
Yeah Hint ignored and its not work please review this question . you should set timeout for javax.persistence.query.timeout
Set timeout on EntityManager query
来源:https://stackoverflow.com/questions/27550663/set-timeout-on-a-typedquery-with-jpa2