【发布时间】:2012-10-16 19:29:13
【问题描述】:
我有一个注入了 EntityManager em 的托管无状态会话 bean。
我想要做的是拥有一个具有唯一列的数据库表。然后我运行一些试图插入实体的算法。但是,如果实体存在,它将更新它或跳过它。
我想要这样的东西:
try {
em.persist(cd);
em.flush();
} catch (PersistenceException e) {
// Check if the exception is DatabaseException and ConstraintViolation
// Update instead or skip it
}
问题是我只能捕捉到PersistenceException。 DatabaseException 未被捕获。很遗憾,因为只有DatabaseException 有一个名为getDatabaseErrorCode() 的方法,我想用它来检查重复条目。我不明白,因为PersistenceException.getCause() 返回DatabaseException。
所以我的问题是:如何捕获DatabaseException 并检查 MySQL 错误代码?
感谢您对此提出任何想法和经验。
【问题讨论】:
-
当你说你的 DatabaseException 没有被捕获时,你的意思是你没有看到它嵌套在 PersistenceException 中吗?类似于:引起:DatabaseException?
-
我看到它嵌套在 PersistenceException 中。但是代码捕获(DatabaseException e)不起作用。如果 DatabaseException 嵌套在 PersistenceException 中,我该如何调用 getDatabaseErrorCode() 方法?也许是它的基本 Java 问题。
标签: java mysql jpa entitymanager