I'm using JPA in Swing based desktop application. This is what my code looks like:
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;
}
I'm using this try - catch - finally
for all methods that requires transaction. It is working as expected, except for methods that has SwingUtilities.invokeLater()
.
finally
will be reached before all code in new thread has been executed; thus, if there is JPA operation inside SwingUtilities.invokeLater()
, it will fail because transaction has been committed.
Is there a generic use case of try - catch - finally
that I can follow to make sure transaction will be committed only after all code has been executed including code inside SwingUtilities.invokeLater()
?