0

我正在使用 JPA Toplink-essential 并开发 RESTful Web 应用程序。

这里首先要提一件事。

不使用 JTA

所以我的persistences.xml 被定义为不使用JTA。

 <persistence-unit name="kojoPU">    
        <provider>oracle.toplink.essentials.PersistenceProvider</provider>
        <non-jta-data-source>machinePrototype</non-jta-data-source>

这允许实体管理器不立即使用 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

但是有一个大问题,在transaction.begin()之后,有没有像JSONExceptionor这样的错误indexOutOfBoundsException事务没有关闭,并保持打开一段时间。

在这种情况下是否可以以某种方式强制关闭交易?

4

1 回答 1

2

除非我错过了什么,否则你可能想要类似的东西:

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
}

但是,我相信事务管理器习惯于在提交失败时回滚,但它似乎并没有发生在你身上。

此外,依赖更新查询在提交时运行并不是一个好主意,因为 Hibernate 可以决定随时运行更新本质上是执行 flush())。如果您想在最后运行查询,请在提交之前执行此操作。

于 2011-02-14T10:46:34.213 回答