java JPA(和/或 Hibernate)-如何设置连接和/或查询的超时阈值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3865399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA (and/or Hibernate) - How to set timeout threshold for connection and/or query?
提问by Jim Tough
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:
我试图弄清楚如何配置我的项目,以便 JPA 在配置的时间后超时并抛出异常。有两种情况我希望这种情况发生:
- 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
- 当 JPA 甚至无法连接到数据库时
- 当 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
- 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) - NOTusing any Hibernate-specific configuration files
- 编码到 JPA 2.0 规范
- 使用 Hibernate 3.5.6 作为 JPA 实现
- 在 Hibernate 中使用 c3p0 连接池
- 使用
persistence.xml
配置文件(仅在必要时使用 Hibernate 特定的属性值) - 不使用任何特定于 Hibernate 的配置文件
回答by DataNucleus
JPA2 persistence property "javax.persistence.query.timeout" allows you to set the timeout for a query (assuming the underlying JDBC driver supports it).
JPA2 持久性属性“javax.persistence.query.timeout”允许您设置查询的超时时间(假设底层 JDBC 驱动程序支持它)。
回答by kisna
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/
您应该同时设置 Java 客户端和数据库服务器默认超时:如果您使用的是 Spring,请使用 @Transactional(timeout=10) 最终设置 PreparedStatement.setQueryTimeout() 提示以在 10 秒内关闭事务。此外,使您的服务器超时略高于客户端超时,以便“java 客户端用户”超时,例如,在 15 秒内:https: //mariadb.com/kb/en/mariadb/query-limits-and-timeouts/
回答by matt b
This page on the Hibernate wikidetails 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)本身上设置的设置。