Spring批量自定义itemWriter,带有插入或更新机制

The*_*rXP 2 database spring jpa upsert spring-batch

我有Spring Batch一个基本的块:

  1. 阅读CSV文件.
  2. 处理它(将一些编码值转码为另一个编码值).
  3. 将结果写入数据库.

问题

在某些情况下,我想在我的自定义中插入或更新机制ItemWriter.

例子:我可以获得这两行 CSV

C006;Test;OK;01/01/1970;1
C006;Test;OK;01/01/1970;5
Run Code Online (Sandbox Code Playgroud)

除了最后一列,你可以发现它们非常相似,策略是:

  1. 如果我有一个"喜欢这样"的实体,请检查数据库
  2. 如果为true,则使用您获得的最后一项更新值(在我们的示例中,最后一列中值为5的第二行)

我做了什么?

在我的实体bean中,我添加了一个Unique Constraint anotation,如下所示:

@Table(name = "indicator",
    uniqueConstraints = { @UniqueConstraint(columnNames = 
                                        { "reference", "type", "status", "date" }) })
Run Code Online (Sandbox Code Playgroud)

我现在肯定我不能坚持使用相同列数据的实体.然后,我创建了一个自定义ItemWriter,我试图捕获ConstraintViolationException,但它不起作用,我总是得到一个其他的exeption,即使我尝试了父的一个.

那么你有什么想法或其他方法吗?

我考虑使用合并JPA功能?你怎么看待这件事?

我的自定义ItemWriter

@Component
public class ImportItemWriter implements ItemWriter<Indicator>{

    @Autowired
    protected IndicatorDao indicatorDao;

    public void write(List<? extends Indicator> items) throws Exception {

        for (Indicator item : items) {
            Indicator indicator = new Indicator();

            indicator.setReference(item.getReference());
            indicator.setType(item.getType());
            indicator.setStatus(item.getStatus());
            indicator.setDueDate(item.getDueDate());

            indicator.setValue(item.getValue());

            try {
                indicatorDao.persist(indicator);
            } catch (ConstraintViolationException e) {
                // TODO: handle exception
            }       
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

解决更新问题 使用的想法Composite PKey很有趣,但我无法使用它,因为我必须使用9个密钥创建一个在性能方面不公平的复合.我决定在my DAO(isDuplicated)中添加函数,在我的自定义中ItemWriter,我只做了一个简单的测试:

if `isDuplicated()` then `updateEntity()` else `insertNew()`
Run Code Online (Sandbox Code Playgroud)

Mic*_*lla 6

一种选择是使用ClassifierCompositeItemWriter.在Classifier将被用来确定是否做插入或更新.然后你配置两个代表,一个用于插入,一个用于更新.