FlatFileParseException解析错误 - Spring Batch

usi*_*sil 4 java spring spring-batch spring-boot

我按照本教程,我收到FlatFileParseException错误:

org.springframework.batch.item.file.FlatFileParseException:资源中的分析错误:1 = [类路径资源[country.csv]],输入= [AA,Aruba]

country.csv

AA,Aruba
BB,Baruba
Run Code Online (Sandbox Code Playgroud)

这是我的ItemReader方法

@Bean
    public ItemReader<Country> reader() {
        FlatFileItemReader<Country> reader = new FlatFileItemReader<Country>();
        reader.setResource(new ClassPathResource("country.csv"));
        reader.setLineMapper(new DefaultLineMapper<Country>() {{
            setLineTokenizer(new DelimitedLineTokenizer() {{
                setNames(new String[] { "countryCode", "countryName" });
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<Country>() {{
                setTargetType(Country.class);
            }});
        }});
        return reader;
    }
Run Code Online (Sandbox Code Playgroud)

Country.java

@Entity
@Table(name="Country")
public class Country  {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    Long id;

    @Column(name = "countryCode", nullable = false, updatable = false)
    String countryCode;

    @Column(name = "countryName", nullable = false, updatable = false)
    String countryName;

    public Country(String countryCode, String countryName) {
        this.countryCode = countryCode;
        this.countryName = countryName;

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    @Override
    public String toString() {
        return "countryCode: " + countryCode + ", countryName: " + countryName;
    }
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 9

这里的问题是你缺少类中的默认无参数构造函数Country.

您正在使用BeanWrapperFieldSetMapper将a映射FieldSet到对象.引用setTargetType(type)Javadoc:

对于每次调用,都将从其默认构造函数创建此类型的对象mapFieldSet(FieldSet).

因此,您需要添加默认构造函数并为属性提供相应的getter/setter.