EntityManager exception handling in session bean

烈酒焚心 提交于 2019-12-09 06:45:55

问题


I have a managed stateless session bean with injected EntityManager em.

What I am trying to do is to have a database table with unique column. Then I run some algorithm which is trying to insert an entity. If entity exists however it will update it or skip it.

I would like to have something like this:

try {   
em.persist(cd);     
em.flush();     
} catch (PersistenceException e) {  
// Check if the exception is DatabaseException and ConstraintViolation
    // Update instead or skip it
}

Problem is that I am able to catch only PersistenceException. DatabaseException is not catched. It is sad because only DatabaseException has method called getDatabaseErrorCode() I would like to use to check duplicate entry. I dont understand it because PersistenceException.getCause() returns DatabaseException.

So my question is: How do I catch DatabaseException and check the MySQL error code?

Thank you for any ideas and experiences with this.


回答1:


I have a suggestion which is I use in my application. We can retrieve the SQLException from PersistenceException. After that, try to get sql error code for SQLException. If your requirement is to get the sql error code, your can follow my example;

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";
}

Example error code configuration of 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 


来源:https://stackoverflow.com/questions/13088499/entitymanager-exception-handling-in-session-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!