gpt4 book ai didi

java - JPA 中回滚语句和事务的区别

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:30 27 4
gpt4 key购买 nike

JPA 查询 javadoc(参见 http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#executeUpdate())说

int executeUpdate() Execute an update or delete statement. 
Returns: the number of entities updated or deleted
Throws:
IllegalStateException - if called for a Java Persistence query language SELECT statement or for a criteria query
TransactionRequiredException - if there is no transaction
QueryTimeoutException - if the statement execution exceeds
the query timeout value set and only the statement is rolled back
PersistenceException - if the query execution exceeds
the query timeout value set and the transaction is rolled back

回滚语句和事务有什么区别?我的意思是,回滚事务非常明显,它将事务设置为回滚并且所有操作都将被撤消。但是如果语句被回滚(因为它是一个更新/删除/插入操作),那么在这种情况下整个事务是不是也被回滚了?

此 QueryTimeoutException 是否旨在被捕获并允许用户在不影响事务的情况下重试超时?

最佳答案

[A QueryTimeoutException is] thrown by the persistence provider when a query times out and only the statement is rolled back. The current transaction, if one is active, will be not be marked for rollback. [QueryTimeoutException]

QueryTimeoutExceptionPersistenceException 的特化.

[A PersistenceException is] thrown by the persistence provider when a problem occurs. All instances of PersistenceException except for instances of NoResultException, NonUniqueResultException, LockTimeoutException, and QueryTimeoutException will cause the current transaction, if one is active and the persistence context has been joined to it, to be marked for rollback. [PersistenceException]

因此,如果查询超时并不重要,默认情况下不会导致事务回滚。这就是为什么您必须始终明确地这样做的原因。例如,如果您想回滚事务,而不管发生哪种 PersistenceException

catch(PersistenceException e) { ... tx.rollback(); ... }

但有时即使语句不成功并且发生 QueryTimeoutException 也需要继续事务。

一个示例场景是在执行仅保留附加日志记录的语句期间超时。根据您的用例,执行日志语句的超时可能并不重要,否则如果核心业务流程(例如坚持订单超时)则很重要。因此,您不希望失败的日志语句影响订单的持久化。另一方面,如果订单的持久化失败,日志记录的持久化应该被回滚。因此,您始终可以决定哪个查询超时应该导致回滚。

一个示意性的例子是

...
try {
...
queryNonCritical.execute(...);
}
catch(QueryTimeoutException e) {
// not critical move on
...
}
...
try {
...
queryCritical.execute(...);
}
catch(QueryTimeoutException e) {
...
tx.rollback();
...
}
...

关于java - JPA 中回滚语句和事务的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503601/

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