简体   繁体   English

JPA(和/或Hibernate) - 如何为连接和/或查询设置超时阈值?

[英]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. 我正在试图弄清楚如何配置我的项目,以便JPA将超时并在配置的时间后抛出异常。 There are two situations where I would like this to happen: 有两种情况我希望这种情况发生:

  • When JPA is unable to even connect to the database 当JPA甚至无法连接到数据库时
  • When a JPA query takes longer than the timeout threshold to return a result set 当JPA查询花费超过超时阈值时返回结果集

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 编码为JPA 2.0规范
  • Using Hibernate 3.5.6 as the JPA implementation 使用Hibernate 3.5.6作为JPA实现
  • Using c3p0 connection pooling with Hibernate 使用c3p0连接池与Hibernate
  • Using persistence.xml configuration file (using Hibernate-specific property values only when necessary) 使用persistence.xml配置文件(仅在必要时使用特定于Hibernate的属性值)
  • NOT using any Hibernate-specific configuration files 使用任何特定于Hibernate的配置文件

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. 您应该同时设置Java客户端以及数据库服务器默认超时:如果您使用的是Spring,请使用@Transactional(timeout = 10),最终设置preparedStatement.setQueryTimeout()提示以在10秒内关闭事务。 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/ 此外,使您的服务器超时略高于客户端超时,以便“java客户端用户”超时,例如,在15秒内: 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. Hibernate wiki上的这个页面详细介绍了如何配置c3p0连接池,包括超时设置。

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. 请注意,这些类型的细节实际上与JPA或Hibernate没有多大关系,但是您在DataSource /数据库连接(本例中为c3p0)本身上设置的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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