2017-05-25 82 views
0

如何處理org.hibernate.exception.ConstraintViolationException?我使用的try-catch,但它不工作:如何處理org.hibernate.exception.ConstraintViolationException,我使用try catch不起作用

try { 
    CandidateCollege newCandidateCollege = candidateCollegeRepo.save(candidateCollege); 
    System.out.println(newCandidateCollege); 
    if(newCandidateCollege != null){ 
     return new WithIncludes<>(newCandidateCollege); 
    } 
} catch (Exception ex) { 
    System.out.println("==========ex.getMessage()============"); 
    log.error(ex.getMessage()); 
} 
return null; 

例外:

2017-05-25 15:52:43 ERROR SqlExceptionHelper:131 - Duplicate entry '270-1-4-2' for key 'ux_candidate_college' 
==========ex.getMessage()============ 
2017-05-25 15:52:43 ERROR CandidateCollegeServiceImpl:67 - could not execute statement; SQL [n/a]; constraint [ux_candidate_college]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement 
+0

好了,不要試圖節省了重複的條目。如果你真的想要捕獲這個異常,請閱讀它的堆棧跟蹤:你會發現它在flush時發生,而不是在調用save()時發生,因爲flush是在Hibernate實際執行插入和更新時發生的。因此,請在您的try塊內部直接調用flush,或者將try塊放在事務之外的更高級別。 –

回答

0

之前保存在數據庫中該條目,您可以檢查是否已經存在與否,如果沒有那麼你可以保存條目。同時指定
catch(ConstraintViolationException cve){ //some appropriate thing to deal with the exception }

這樣您還可以處理您正在尋找的特定異常情況!

+2

可能是因爲在保存之前檢查是否存在更好的辦法,因爲它會花費另一次往返數據庫。在正確的點處理異常將是性能健康@coolgirl –

0

看看輸出,我會說catch塊被執行。注意輸出中的=====。上面的消息只是Hibernate的內部日誌記錄。我希望你的方法確實返回null。你檢查過了嗎?

0

它不會捕捉到您的異常,因爲ConstraintViolationException是在交易刷新時拋出的,實際上在您的try-catch塊或save()呼叫之間不會發生。

你可以圍繞try-catch在一些更高的水平像例如。在控制器,你可以檢查ConstraintViolationException被拋出並採取行動的協議。

還是可以沖洗您的交易後,明確save()

+0

謝謝,非常有幫助! –