java - 捕获Spring数据异常

标签 java spring spring-data-jpa spring-data

我尝试保留实体列表:

for (Charge charge : charges) {
      try {
        Charge savedCharge = saveCharge(charge);
      }catch (DataAccessException e){
        log.error(e.getMessage());
      }
    }

public Charge saveCharge(Charge charge){
    return chargesRepository.save(charge);
  }

有时我会遇到异常(exception):

Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: the limitation of uniqueness has been violated

我需要捕获这个异常。我该怎么做?

最佳答案

您将其捕获为任何异常。不过我建议你还是捕获 DataIntegrityViolationException来自 Spring 框架,因为 Spring 已经将 SQL 异常转换为更具体的异常:

try {
    Charge savedCharge = saveCharge(charge);
} catch (DataIntegrityViolationException e) {
    log.error(e.getMessage());
    // more error handling actions
} // more catch clauses

关于java - 捕获Spring数据异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839776/

相关文章:

java - 使用 logback 格式化日志

java - 数据库表中的 Quartz 作业

java - Spring-data-jpa - .save() 什么时候不返回相同的实体?

java - org.springframework.data.mongodb.core.mapping.Document无法引用

java - Maven 无法解析 org.apache.velocity lib

java - 如何从代码访问 MenuBar 的 CSS 样式规则 - GWT

java - 如何解决 LI_LAZY_INIT_UPDATE_STATIC?

java - 尝试在 Java 中使用递归任务(Fork 和 Join)计算 (3*3)^2 时出错

java - Spring 4 - 带有服务的自定义 SecurityExpression

postgresql - 使用 PostgreSQL JSONB 的 Spring JPA 排序和分页