Swing ベースのデスクトップ アプリケーションで JPA を使用しています。これは私のコードがどのように見えるかです:
public Object methodA() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
boolean hasError = false;
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// JPA operation does not work here
// because transaction has been committed!
}
});
...
return xXx;
} catch (Exception ex) {
hasError = true;
em.getTransaction().rollback();
} finally {
em.close();
if (!hasError) {
em.getTransaction().commit();
}
}
return null;
}
try - catch - finally
トランザクションを必要とするすべてのメソッドにこれを使用しています。を持つメソッドを除いて、期待どおりに機能していSwingUtilities.invokeLater()
ます。
finally
新しいスレッドのすべてのコードが実行される前に到達します。したがって、 内SwingUtilities.invokeLater()
に JPA 操作がある場合、トランザクションがコミットされているため失敗します。
try - catch - finally
内部のコードを含むすべてのコードが実行された後にのみトランザクションがコミットされることを確認するために従うことができる一般的なユースケースはありSwingUtilities.invokeLater()
ますか?