2016-10-31 48 views
0

有兩個數據庫表role和role_menu。 role_menu引用角色的主鍵有外鍵。如何捕獲完整性約束刪除錯誤?

現在我正在刪除一行主表角色,該行有一個與role_menu關聯的外鍵。我試圖包圍Try Catch中刪除代碼,但執行並不在catch塊輸入:

@Override 
@Transactional 
public void delete(String role_code) { 
    try { 
    sessionFactory.getCurrentSession().delete((Role) sessionFactory.getCurrentSession().get(Role.class, role_code)); 
    } catch (Exception e) { 
     System.out.println("error : there is fk !"); 
    } 

} 

在控制檯中我得到了這些文本:

WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 2292, SQLState: 23000 
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ORA-02292: integrity constraint (PTA.FK_ROLE_MEN_R_ROLE_ME_ROLE) violated - child record found 

那麼如何應對完整性約束缺失錯誤?

回答

1

問題來自事實,即僅在事務提交之前將會話刷新到數據庫時引發異常。由於您使用的是@Transactional註釋,它正好在catch塊之後的方法結束時發生。在try塊的末尾沖洗會議應該做的伎倆:

@Override 
@Transactional 
public void delete(String role_code) { 
    try { 
     Session session = sessionFactory.getCurrentSession(); 
     session.delete((Role) session.get(Role.class, role_code)); 
     session.flush(); 
    } catch (Exception e) { 
     System.out.println("error : there is fk !"); 
    } 
} 

注意,這可能是最好避免使用沖洗那裏捕獲異常在另一個層面,但是這取決於使用情況。

+0

因爲事務已經被標記爲回滾,所以你不能在另一個級別捕獲它。無論如何,這一切都是一個非常糟糕的主意,並打破了幾個原則。 http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/Session.html「如果會話引發異常,則必須回滾事務並丟棄會話。會話的內部狀態發生異常後可能與數據庫不一致。「 – Gab

+0

在另一個級別捕獲異常意味着事務也在其他級別創建,然後傳播到此函數中。 –

相關問題