会话bean中的EntityManager异常处理

Mac*_*kou 4 java mysql jpa entitymanager

我有一个带有注入的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
}
Run Code Online (Sandbox Code Playgroud)

问题是我只能抓到PersistenceException.DatabaseException没有被抓住.这是可悲的,因为只有DatabaseException已调用的方法getDatabaseErrorCode(),我想用它来检查重复的条目.我不理解它因为PersistenceException.getCause()回归DatabaseException.

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

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

Zaw*_* oo 6

我有一个建议,我在我的申请中使用.我们可以检索SQLException来自PersistenceException.在此之后,尝试获得sql error codeSQLException.如果你的要求是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";
}
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)