java - JPA 与非 JTA : Is it possible to close EntityTransaction safely without commit?

标签 java jpa transactions toplink-essentials

我正在使用 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()之后,是否有类似JSONExceptionindexOutOfBoundsException的错误,事务没有关闭并且保持开放一段时间。

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

最佳答案

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

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())。如果您想在最后运行查询,请在提交之前执行。

关于java - JPA 与非 JTA : Is it possible to close EntityTransaction safely without commit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4991158/

相关文章:

postgresql - 如何在PostgreSQL中实现 `BEGIN ATOMIC`

java - Spring 交易未提交

java - VM 初始化期间发生错误 java/lang/NoClassDefFoundError : java/lang/Object

java - 在 Android 中以编程方式创建具有自定义列表项的 ListView - 无 xml 列表项布局

java - 是否可以为重载方法获取相同的文档?

java - 在用 spring 的 @Transactional 注释的方法中抛出并捕获未经检查的异常是否仍会导致事务回滚?

带有 JPA : move @Entity to different package 的 Spring Boot

java - 单击取消按钮 showInputDialog

java - JPA 来自同一个表的多个 FK

spring - PROPAGATION_NESTED vs PROPAGATION_ Spring 需要吗?