0

私はJPAToplinkを使用しています-必須でRESTfulWebアプリを開発しています。

ここで最初に言及することが1つあります。

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

JSONExceptionしかし、transaction.begin()の後に、またはindexOutOfBoundsExceptionのようなエラーがあるという大きな問題が1つあります。トランザクションは閉じられず、しばらく開いたままになります。

そのような場合、どういうわけかトランザクションを強制的に閉じることは可能ですか?

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 に答える