将具有列表的对象另存为csv文件FlatFileItemWriter [英] Save object with List as csv file FlatFileItemWriter

查看:86
本文介绍了将具有列表的对象另存为csv文件FlatFileItemWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似(抽象描述)的对象

I have an object like (abstract description)

public class Book {
private String name;
private List<Author> authors;
}
public class Author {
private String name;
}

例如

 new Book()
 .setName("Book name1")
 .setAuthors(new ArrayList(Arrays.asList(
      new Author().setName("Author 1"), 
      new Author().setName("Author 2"))));

示例代码:

@Bean
public FlatFileItemWriter<Book> writer()
{
    FlatFileItemWriter<Book> writer = new FlatFileItemWriter<>();
    writer.setResource(outputResource);
    writer.setAppendAllowed(true);
    writer.setLineAggregator(new DelimitedLineAggregator<Book>() {
        {
            setDelimiter(";");
            setFieldExtractor(new BeanWrapperFieldExtractor<Book>() {
                {
                    setNames(new String[] { "name", "authors" });
                }
            });
        }
    });
    return writer;
}

这样我得到结果:

Book name1;[Author(authorName=Author 1), Author(authorName=Author 2)]

但是我想将结果csv文件保存为:

But I want to get result csv file as:

Book name1;Author 1
Book name1;Author 2

帮助我了解它是如何工作的.预先感谢.

Help me to understand, how does it work. Thanks in advance.

推荐答案

帮助我了解它是如何工作的

Help me to understand, how does it work

BeanWrapperFieldExtractor 是一个字段提取器,它在输入对象的每个字段上调用getter.这是其 Javadoc :

The BeanWrapperFieldExtractor is a field extractor that call getters on each field of your input object. Here is an excerpt from its Javadoc:

Given an array of property names, it will reflectively call getters on the item
and return an array of all the values.

在您的情况下,调用字段 authors 的获取方法将导致 List 对象的 toString()值:

In your case, calling the getter of the field authors results in the toString() value of a List object:

[Author(authorName=Author 1), Author(authorName=Author 2)]

但是,由于您希望将每本输入书写成多行,而每位作者写一行,因此您实际上要进行的是平面图操作.有很多方法可以做到,春季批处理中的平整处理结果中描述了其中一种..

However, what you are trying to do is actually a flatmap operation, since you want each input book to be written as multiple lines, one line for each author. There are many ways to do that, one of them is described in Flatten processing result in spring batch.

这篇关于将具有列表的对象另存为csv文件FlatFileItemWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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