【问题标题】:Save object with List as csv file FlatFileItemWriter将带有 List 的对象另存为 csv 文件 FlatFileItemWriter
【发布时间】:2021-02-12 11:15:07
【问题描述】:

我有一个像(抽象描述)这样的对象

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 文件为:

Book name1;Author 1
Book name1;Author 2

帮助我了解它是如何工作的。 提前致谢。

【问题讨论】:

  • 我添加了一个答案,有帮助吗?

标签: java spring-boot spring-batch export-to-csv


【解决方案1】:

帮助我理解,它是如何工作的

BeanWrapperFieldExtractor 是一个字段提取器,它在输入对象的每个字段上调用 ​​getter。以下是其Javadoc的摘录:

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

在您的情况下,调用字段authors 的getter 会产生toString() 对象的toString() 值:

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

但是,您尝试做的实际上是平面图操作,因为您希望将每本输入书写成多行,每个作者一行。有很多方法可以做到这一点,Flatten processing result in spring batch 中描述了其中一种。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2019-07-28
    • 2014-03-13
    • 1970-01-01
    • 2020-11-03
    • 2015-05-11
    相关资源
    最近更新 更多