【问题标题】:Spring batch handle ConstraintViolationExceptionSpring批处理处理ConstraintViolationException
【发布时间】:2018-02-02 22:43:23
【问题描述】:

我正在使用 Spring Batch 导入城市数据。

City{
  String name;
  @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
  State state;
}
State{
  String name;
  String code;
}

我已经在 fieldSetMapper 中填充了所需的数据,在处理器中,我需要设置州和城市之间的关系。

State state;
if ((state = stateDao.findByStateCode(city.getState().getStateCode())) != null) {
  city.setState(state);
} else {
  city.getState().setCountry(country);
}

由于spring batch使用chunk来处理事务,所以如果同一个chunk中的多个城市有相同的state,而state repository还没有存储,就会导致唯一性约束违规。

例如,2 个城市行

{name:x, state:{name:xx,code:xy}}
{name:y, state:{name:xx,code:xy}}

当spring批处理写入第一行时,它将创建一个名称为xx,代码为xy的新状态。但是对于第二行,由于该状态已经在数据库中,它将抛出constraintviolationexception。如果抛出异常,有没有办法重新处理第二行? retry() 也会回滚第一行。

谢谢。

【问题讨论】:

    标签: spring-batch


    【解决方案1】:

    我还没有解决这个问题,但我设法通过一次分块一个项目而不是 10 个项目来避免这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 2014-12-03
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2015-08-19
      相关资源
      最近更新 更多