[英]JPA with non-JTA: Is it possible to close EntityTransaction safely without commit?
I'm using JPA Toplink-essential and developing RESTful web app. 我正在使用JPA Toplink-essential和开发RESTful Web应用程序。
Here is one thing to mention first. 首先要提到一件事。
Not using JTA 不使用JTA
So my persistences.xml is defined not to use JTA. 所以我的persistences.xml被定义为不使用JTA。
<persistence-unit name="kojoPU">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<non-jta-data-source>machinePrototype</non-jta-data-source>
This allows the entity manager not to execute query immediately with executeUpdate() It will wait til commit. 这允许实体管理器不使用executeUpdate()立即执行查询。它将等待提交。
em.getTransaciton().begin();
Query query = em.createNativeQuery("DELETE FROM table1 WHERE theId = 10;");
query.executeUpdate(); //not yet executed until transaction is commited.
//continue do something...
em.getTransaction().commit(); //the query above is executed here finally
But there is one big problem, after transaction.begin(), is there is any error like JSONException
or indexOutOfBoundsException
, the transaction is not closed and kept open for a while. 但是有一个大问题,在transaction.begin()之后,如果有任何错误,如
JSONException
或indexOutOfBoundsException
, 则事务未关闭并保持打开一段时间。
Is it possible to force close the transaction somehow in such case? 在这种情况下,是否有可能以某种方式强制关闭交易?
Unless I missed something, you probably want something like: 除非我错过了什么,否则你可能会想要:
em.getTransaciton().begin();
try {
Query query = em.createNativeQuery("DELETE FROM table1 WHERE theId = 10;");
query.executeUpdate(); //not yet executed until transaction is commited.
//continue do something...
em.getTransaction().commit(); //the query above is executed here finally
} catch (ex RuntimeException) {
em.getTransaction().rollback();
} finally {
// you probably also want something here to check the status of the transaction and rollback if you exited the try block somehow
}
However, I believe it's customary for transaction manager to rollback on commit failure but it seems like it's not happening for you. 但是,我相信事务管理器会在提交失败时回滚,但这似乎对您来说没有发生。
Also, relying on the update query to run on commit is not a good idea since Hibernate can decide to run your update at any time (essentially doing a flush()). 此外,依靠更新查询上运行犯不是个好主意,因为Hibernate可以决定运行在任何时间更新(主要做的flush())。 If you want to run the query at the very end, do it right before your commit.
如果您想在最后运行查询,请在提交之前进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.