如何处理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;
异常(exception):
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
最佳答案
它不会捕获您的异常,因为在事务刷新时抛出 ConstraintViolationException
,而这实际上并没有发生在您的 try-catch
block 之间或 期间save()
调用。
您可以将 try-catch
包围在更高的级别,例如。在 Controller 中,您可以检查是否抛出了 ConstraintViolationException
并根据情况采取行动。
或者可以在save()
之后显式刷新您的交易
关于java - 如何处理 org.hibernate.exception.ConstraintViolationException,我使用 try catch 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175413/