【问题标题】:Is there any way to handle org.springframework.dao.DataIntegrityViolationException for unique constraint in saveAll of CrudRepository of Spring Boot?有没有办法处理 org.springframework.dao.DataIntegrityViolationException 在 Spring Boot CrudRepository 的 saveAll 中的唯一约束?
【发布时间】:2021-11-05 18:47:51
【问题描述】:

我想一次保存多个对象,为此我在 Spring Boot 中使用 CrudRepository 的 saveAll 方法。但是对象在mysql中有一个具有唯一约束的属性。因此,当我尝试 saveAll 方法时,它向我显示重复条目异常,即 org.springframework.dao.DataIntegrityViolationException。 我想保存所有其他不会出现重复条目​​异常的对象。 任何人都可以有这种要求吗?如果您有任何解决方案,请告诉我。

【问题讨论】:

  • 保存前过滤?
  • @yoni 用于过滤我必须检查每条记录以及数据库中存在的每条记录。对于大量记录,这需要时间。

标签: java mysql spring spring-boot


【解决方案1】:

不要使用 saveAll 方法,而是使用下面的方法

for(int i=0; i<list.size(); i++) {
            try {
               save(list.get(i));
            } catch(DataIntegrityViolationException e){
            continue;
         }
      }

【讨论】:

  • 是否可以使用 saveAll 方法捕获异常?实际上,我有大量记录要一次保存。一次保存单条记录会花费更多时间,对吗?
  • stackoverflow.com/questions/64754720/… - 看看这个,它可能会解决你的问题..
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
相关资源
最近更新 更多