2012-10-26 50 views
4

我有一個託管的無狀態會話bean,它帶有注入的EntityManager em。會話bean中的EntityManager異常處理

我想要做的是有一個獨特的列的數據庫表。然後我運行一些試圖插入實體的算法。如果實體存在,但它會更新它或跳過它。

我想有這樣的事情:

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錯誤代碼?

感謝您對此有任何想法和經驗。

+0

當你說你的DatabaseException也不會鉤住你的意思是你沒有看到它在嵌套的PersistenceException?像這樣:引起:DatabaseException? – nwallman

+0

我看到它嵌套在PersistenceException中。但是代碼catch(DatabaseException e)不起作用。如果DatabaseException嵌套在PersistenceException中,我該如何調用方法getDatabaseErrorCode()?也許它的基本Java問題。 – Macejkou

回答

6

我有一個建議,我在我的應用程序中使用。我們可以從PersistenceException檢索SQLException。之後,嘗試獲取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"; 
} 

示例錯誤代碼的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