0

我有一个具有唯一约束的字段:

@Column(unique=true)
private String uriTitle;

当我尝试保存具有相同值的两个实体时,我得到一个异常 - 但另一个异常不是我执行的:

java.lang.IllegalStateException: <|Exception Description: No transaction is currently active
        at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:122)
        at com.example.persistence.TransactionFilter.doFilter(TransactionFilter.java:35)

有问题的过滤方法如下所示:

public void doFilter(ServletRequest request, ServletResponse response,
          FilterChain chain)
          throws IOException, ServletException {
    EntityManager entityManager = ThreadLocalEntityManager.get();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    try {
      chain.doFilter(request, response);
      transaction.commit();
    }
    catch (Throwable t) {
      transaction.rollback();  // line 35, mentioned in the exception
      throw new RuntimeException(t);
    }
    finally {
      entityManager.close();
      ThreadLocalEntityManager.reset();
    }
}

...和这样的 ThreadLocalEntityManager :

public class ThreadLocalEntityManager {

    private static EntityManagerFactory entityManagerFactory = null;
    private static final ThreadLocal<EntityManager> entityManager =
        new ThreadLocal<EntityManager>() {
            @Override 
            protected EntityManager initialValue() {
                return entityManagerFactory.createEntityManager();
            }
        };

    private ThreadLocalEntityManager() {}

    public static synchronized void init(String persistenceUnit) {
        requireNotNull(persistenceUnit);
        requireState(entityManagerFactory == null, "'init' can be called only "
                        + "once.");
        entityManagerFactory =
                        Persistence.createEntityManagerFactory(persistenceUnit);
    }

    public static EntityManager get() {
        requireState(entityManagerFactory != null, "Call 'init' before calling "
                        + "'get'");
        return entityManager.get();
    }

    public static void reset() {
        entityManager.remove();
    }

}

我包装了对 with 的调用以save处理try ...catch违反唯一约束的情况,但这不起作用:

try {
    ThreadLocalEntityManager.get().persist(article); // article is constrained
}
catch(Throwable t) {
    t.printStackTrace();
}

知道为什么没有交易吗?处理唯一约束违规的正确方法是什么?

4

2 回答 2

2

由于违反数据库约束,您的事务自动回滚,因此没有需要手动回滚的事务。要处理这种情况,您可以编写

catch (Throwable t) {
  if (transaction.isActive()) 
    transaction.rollback();  // line 35, mentioned in the exception 
  throw new RuntimeException(t); 
}
于 2010-08-17T11:26:52.833 回答
0

您的应用程序中的事务和 GUI 之间没有任何分离。通常,您将遇到事务处理问题。

于 2012-10-16T11:39:35.207 回答