tags:

views:

454

answers:

2

I am doing some big queries on my database with Hibernate and I sometimes hit timeouts. I would like to avoid setting the timeout manually on every Query or Criteria.

Is there any property I can give to my AnnotationConfiguration that would set an acceptable default for all queries I run?

If not, how can I set a default timeout value on Hibernate queries?

A: 

Here are a few ways:

  • Use a factory or base class method to create all queries and set the timeout before returning the Query object
  • Create your own version of org.hibernate.loader.Loader and set the timeout in doQuery
  • Use AOP, e.g. Spring, to return a proxy for Session; add advice to it that wraps the createQuery method and sets the timeout on the Query object before returning it
Brian Deterling
I thought of doing the first option you gave at first, but I thought "surely, Hibernate offers a way to avoid this!"About the Loader, I'm not too excited about creating a new one in full. But I thought that maybe I can extend `BasicLoader`. The thing is, I don't see a `doQuery` in that API:https://www.hibernate.org/hib_docs/v3/api/org/hibernate/loader/Loader.htmlSo, I would have to override which methods? I'm guessing `doList`, `getResultSet`, `prepareQueryStatement` and `scroll`. Am I right?
mlaverd
I could be wrong but I don't think Hibernate lets you hook into the loader that way. I copied the hibernate loader from source into my project using the same package as Hibernate; since my classes are ahead of Hibernate in the classpath, mine gets used. The only downside is you have to do that each time you upgrade Hibernate. But if you can get to the PreparedStatement object before the query runs, you can call setQueryTimeout, so prepareQueryStatement might be your best bet.
Brian Deterling
A: 

JPA 2 defines the javax.persistence.query.timeout hint to specify default timeout in milliseconds. Hibernate 3.5 (currently still in beta) will support this hint.

See also http://opensource.atlassian.com/projects/hibernate/browse/HHH-4662

Hardy
I'm not too excited about building on a beta... Having a look at the site, I don't see an expected release date. Do you know when they're planning to release it?
mlaverd
The CR release is only a couple of weeks away and I would think that 3.5 will follow shortly after. JPA 2 compliance is high on the priority list, so there is no risk that the issue would fall under the table.
Hardy