【问题标题】:EntityManager exception handling in session bean会话 bean 中的 EntityManager 异常处理
【发布时间】: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
}

问题是我只能捕捉到PersistenceExceptionDatabaseException 未被捕获。很遗憾,因为只有DatabaseException 有一个名为getDatabaseErrorCode() 的方法,我想用它来检查重复条目。我不明白,因为PersistenceException.getCause() 返回DatabaseException

所以我的问题是:如何捕获DatabaseException 并检查 MySQL 错误代码?

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

【问题讨论】:

  • 当你说你的 DatabaseException 没有被捕获时,你的意思是你没有看到它嵌套在 PersistenceException 中吗?类似于:引起:DatabaseException?
  • 我看到它嵌套在 PersistenceException 中。但是代码捕获(DatabaseException e)不起作用。如果 DatabaseException 嵌套在 PersistenceException 中,我该如何调用 getDatabaseErrorCode() 方法?也许是它的基本 Java 问题。

标签: java mysql jpa entitymanager


【解决方案1】:

我有一个建议在我的应用程序中使用。我们可以从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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2014-10-22
    相关资源
    最近更新 更多