简体   繁体   中英

JPA (and/or Hibernate) - How to set timeout threshold for connection and/or query?

I'm trying to figure out how to configure my project such that JPA will timeout and throw an exception after a configured amount of time. There are two situations where I would like this to happen:

  • When JPA is unable to even connect to the database
  • When a JPA query takes longer than the timeout threshold to return a result set

I'm not sure if these two scenarios can be configured separately (a different timeout threshold for each), or if one threshold is used for both.

My project is currently set up as follows:

  • Coding to the JPA 2.0 specification
  • Using Hibernate 3.5.6 as the JPA implementation
  • Using c3p0 connection pooling with Hibernate
  • Using persistence.xml configuration file (using Hibernate-specific property values only when necessary)
  • NOT using any Hibernate-specific configuration files

JPA2持久性属性“javax.persistence.query.timeout”允许您设置查询的超时(假设底层JDBC驱动程序支持它)。

You should be setting both Java client as well as database server default timeouts: If you were using Spring, use @Transactional(timeout=10) which eventually sets the preparedStatement.setQueryTimeout() hint to close the transaction within 10 seconds. Also, enable your server to timeout slightly above the client timeout so "java client user" to timeout, say, in 15 s: https://mariadb.com/kb/en/mariadb/query-limits-and-timeouts/

This page on the Hibernate wiki details how to configure the c3p0 connection pool, including the timeout settings.

Note that these type of details really don't have much to do with JPA or Hibernate, but are settings that you set on the DataSource / database connection (c3p0 in this case) itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM