gpt4 book ai didi

java - 使用 JPA2 设置 TypedQuery 的超时

转载 作者:行者123 更新时间:2023-12-01 17:01:11 26 4
gpt4 key购买 nike

我想在 javax.persistence.TypedQuery 上设置超时。

我发现了这个简单的方法:

TypedQuery<Foo> query = ... ;
query.setHint("javax.persistence.query.timeout", 1000);
query.getReturnList();

但似乎不起作用,它只是被忽略了。

摘自PRO JPA 2一书:

"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."

有人知道在 TypedQuery 上指定超时的任何其他方法吗?

或者我怎样才能让这个“提示”发挥作用?

谢谢

编辑:Oracle 11.2.0.4.0 和 PostgreSql 9.2.9使用 JPA 2.1/Hibernate

最佳答案

我知道回复晚了,但我们在 Oracle 11g、JPA2.0 中遇到了类似的问题,并且此提示不起作用。

实际上,问题是我们将它用作 @NamedQuery 提示,并在 @transactional 方面调用该函数。由于 @NamedQuery 在上下文加载时加载并编译,因此该超时被事务超时覆盖。您可以在 http://javadeveloperz0ne.blogspot.in/2015/07/why-jpa-hints-on-namedquery-wont-work.html 找到更多信息。

解决方案将再次获取命名查询,然后应用超时。

Query query = entityManager.createNamedQuery("NamedQueryName");
query.setHint("org.hibernate.timeout", "5");
query.getSingleResult();

希望对你有帮助!

关于java - 使用 JPA2 设置 TypedQuery 的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27550663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com