Spring Batch - 使用带有列表列表的ItemWriter [英] Spring Batch - Using an ItemWriter with List of Lists

查看:209
本文介绍了Spring Batch - 使用带有列表列表的ItemWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的处理器返回列表<?> (有效传递列表< List<?>> )到我们的 ItemWriter

Our processor returns a List<?> (effectively passing a List<List<?>>) to our ItemWriter.

现在,我们发现 JdbcBatchItemWriter 未被编程为处理 item instanceof List 。我们还观察到处理项目instanceof List ;我们需要编写一个自定义 ItemSqlParameterSourceProvider

Now, we observed that the JdbcBatchItemWriter is not programmed to handle item instanceof List. We also observed to process item instanceof List; we need to write a custom ItemSqlParameterSourceProvider.

但令人遗憾的是,它返回 SqlParameterSource ,它只能处理一个并且再次无法处理列表

But the sad part is that it returns SqlParameterSource which can handle only one item and again not capable of handling a List.

那么,是否有人可以帮助我们了解如何处理 JdbcBatchItemWriter 中的列表列表?

So, can someone help us understand how to handle list of lists in the JdbcBatchItemWriter?

推荐答案

通常,设计模式为:

Reader -> reads something, returns ReadItem
Processor -> ingests ReadItem, returns ProcessedItem
Writer -> ingests List<ProcessedItem>

如果您的处理器返回 List< Object> ,那么你需要你的作家期望列表< List< Object>>

If your processor is returning List<Object>, then you need your Writer to expect List<List<Object>>.

你可以这样做将 JdbcBatchItemWriter 包装为ItemWriter中的委托,如下所示:

You could do this by wrapping your JdbcBatchItemWriter as a delegate in an ItemWriter that looks something like this:

public class ListUnpackingItemWriter<T> implements ItemWriter<List<T>>, ItemStream, InitializingBean {

    private ItemWriter<T> delegate;

    @Override
    public void write(final List<? extends List<T>> lists) throws Exception {
        final List<T> consolidatedList = new ArrayList<>();
        for (final List<T> list : lists) {
            consolidatedList.addAll(list);
        }
        delegate.write(consolidatedList);
    }

    @Override
    public void afterPropertiesSet() {
        Assert.notNull(delegate, "You must set a delegate!");
    }

    @Override
    public void open(ExecutionContext executionContext) {
        if (delegate instanceof ItemStream) {
            ((ItemStream) delegate).open(executionContext);
        }
    }

    @Override
    public void update(ExecutionContext executionContext) {
        if (delegate instanceof ItemStream) {
            ((ItemStream) delegate).update(executionContext);
        }
    }

    @Override
    public void close() {
        if (delegate instanceof ItemStream) {
            ((ItemStream) delegate).close();
        }
    }

    public void setDelegate(ItemWriter<T> delegate) {
        this.delegate = delegate;
    }

}

这篇关于Spring Batch - 使用带有列表列表的ItemWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆