会话bean中的EntityManagerexception处理

我有一个带有注入的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错误代码?

感谢您对此的任何想法和经验。

我有一个建议,我在我的申请中使用。 我们可以从PersistenceException检索SQLException 。 之后,尝试获取SQLException sql error code 。 如果您的要求是获取sql error code ,您可以按照我的示例;

 public void insert(Group group) throws DAOException { try { //your operation em.flush(); logger.debug("insert() method has been successfully finisehd."); } catch (PersistenceException pe) { String sqlErroCode = getErrorCode(pe); // do your operation based on sql errocode } } protected String getErrorCode(RuntimeException e) { Throwable throwable = e; while (throwable != null && !(throwable instanceof SQLException)) { throwable = throwable.getCause(); } if (throwable instanceof SQLException) { Properties properties = --> load sql error code form configuration file. SQLException sqlex = (SQLException) throwable; String errorCode = properties.getProperty(sqlex.getErrorCode() + ""); return errorCode; } return "NONE"; } 

mysql的示例错误代码配置

mysql_error_code.properties

 #MySQL Database 1062=DUPLICATE_KEY_FOUND 1216=CHILD_RECORD_FOUND 1217=PARENT_RECORD_NOT_FOUND 1048=NULL_VALUE_FOUND 1205=RECORD_HAS_BEEN_LOCKED