java - 如何处理 org.hibernate.exception.ConstraintViolationException,我使用 try catch 不起作用

标签 java hibernate

如何处理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/

相关文章:

java - 使用级联持久化实体时获取子id

java - webapp中使用的Spring-Hibernate,线程安全 session 管理的策略是什么

java - 安卓用户界面 : Positioning of custom GIF View within RelativeLayout

java - 我如何在 spigot api 中的命令上打印可点击的链接

java - 如何查找 3D 数组索引值

java - 加载实体而不锁定数据库中的行

java - 在单词和引号之间分割字符串

java - JUnit Eclipse 与 Ant

java - @Transactional(readOnly = false,propagation = Propagation.REQUIRED)抛出异常

angularjs - JsonException 未分配 _valueDeserializer