我在基于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()内部的代码)后才提交事务?

最佳答案

您必须重新考虑您的方法。首先,SwingUtilities.invokeLater()不是执行JPA操作的最佳选择。该实用程序方法的主要目的是更新UI。关于您的代码,为JPA操作实现单独的线程,该线程将使用事务状态的侦听器。交易完成后,您将更新UI。

/**
 * Transaction callback.
 */
public interface TransactionListener {
    void onTransactionFinished(boolean hasError);
}

/**
 * Worker Thread which takes data and performs JPA operations.
 */
public class JPATask implements Runnable {
    private final Object dataToPersist;
    private final TransactionListener transactionListener;

    public JPATask(Object dataToPersist,
            TransactionListener transactionListener) {
        this.dataToPersist = dataToPersist;
        this.transactionListener = transactionListener;
    }

    private EntityManager getEntityManager() {/* code is omited */}

    @Override
    public void run() {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            // perform JPA actions here
            em.getTransaction().commit();
            transactionListener.onTransactionFinished(false);
        } catch (Exception ex) {
            em.getTransaction().rollback();
            transactionListener.onTransactionFinished(true);
        }
    }
}

/**
 * Finally you method. Now it looks like this.
 */
public Object methodA() {
    JPATask jpaTask = new JPATask(<data to persist>, new TransactionListener() {
        @Override
        public void onTransactionFinished(boolean hasError) {
            // Update UI. It's time to use SwingUtilities.invokeLater()
        }
    }).start();
}

10-08 07:24