我有一个具有唯一约束的字段:
@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();
}
知道为什么没有交易吗?处理唯一约束违规的正确方法是什么?