2010-08-17 91 views
19

違反唯一性約束時,將引發javax.persistence.RollbackException。但可能有多種理由拋出RollbackException。我怎麼能發現一個獨特的約束被違反?如何處理JPA唯一約束違規?

try { 
    repository.save(article); 
} 
catch(javax.persistence.RollbackException e) { 
    // how to find out the reason for the rollback exception? 
} 

回答

17

我如何知道違反了唯一約束條件?

異常的鏈接,你必須調用getCause()遞歸以獲得供應商特定的例外(也許再往SQLException)把它翻譯成你的應用程序可以很好地處理了您的用戶。下面將打印異常鏈:

for (t = e.getCause(); t != null; t = t.getCause()) { 
    logger.debug("Exception:" + t); 
} 

對於異常處理和「翻譯」,你可以不喜歡什麼Spring並不是(見各JpaDialect類,如HibernateJpaDialect得到一個想法)。

所有這些都不好,這段代碼不能移植,找到哪些屬性會導致違規並不容易。這不知何故證實,沒有elegant and portable way to handle constraint violations in JPA

3

使用e.getCause()來檢查導致回滾的原因。

+0

...然後解析'getCause()。getMessag()'? – deamon 2010-08-17 12:28:47

+0

這取決於你會得到什麼異常。如果它是'SQLException',則檢查錯誤和SQLStatus。但是一些像Spring這樣的框架將它們轉化爲更有意義的東西('DataIntegrityViolationException')。 – 2010-08-18 07:38:09

0

我認爲打印堆棧跟蹤將幫助你知道這一點。 e.printStackTrace();

+0

我不打算手動處理異常:-) – deamon 2010-08-17 14:36:11

0

你可以這樣做:

StringWriter writer=new StringWriter(); //remains the message from stack trace. 
e.printStackTrace(new PrintWriter(writer)); 
String message=writer.toString(); // gets the message of full stack trace. 

然後查看異常的信息。

+0

好的,但我該怎麼處理StackTrace?用堆棧跟蹤解析字符串有點難看,但也許是唯一的可能性。 – deamon 2010-08-17 14:38:05

+1

我怎麼知道什麼領域造成違反約束? – deamon 2010-08-17 15:23:28

1

編譯器返回異常SQLIntegrityConstraintViolationException,同時試圖違反唯一約束。

使用以下catch塊概念來處理適當的異常。

catch(SQLIntegrityConstraintViolationException e) 
{ 
    // Error message for integrity constraint violation 
} 
catch(Exception e) 
{ 
// Other error messages 
} 
相關問題