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