spring-batch读入null int值

时间:2018-04-25 10:53:23

标签: java spring-boot spring-batch

我有一个文件阅读器来阅读客户csv文件 如果int字段为空 我收到错误Field error in object 'target' on field 'custPaymentTerm': rejected value []; codes [typeMismatch.target.custPaymentTerm,typeMismatch.custPaymentTerm,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.custPaymentTerm,custPaymentTerm]; arguments []; default message [custPaymentTerm]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'custPaymentTerm'; nested exception is java.lang.NumberFormatException: For input string: ""]

要读取文件的类。 spring-batch-job如何读取,处理null int值。

我的csv数据文件的第二行抛出空错误!

public static void readCustomers(String pathToFile) throws Exception {  
     System.out.println(" THE path is:"+pathToFile);
     FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
     reader.setResource(new FileSystemResource(pathToFile));


     DelimitedLineTokenizer delimitedTokeniser = new DelimitedLineTokenizer();
     delimitedTokeniser.setNames(new String[]{"valueA", "custPaymentTerm","valueC"});
     DefaultLineMapper<Customer> lineMapper = new DefaultLineMapper<Customer>();
     lineMapper.setLineTokenizer(delimitedTokeniser);
     lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<Customer>() {{setTargetType(Customer.class);}});
     reader.setLineMapper(lineMapper);
     reader.setLinesToSkip(1); //do not read the first line of the csv file.
     reader.open(new ExecutionContext());
     Customer store = null;
     List<Customer> stores = new ArrayList<>();
     do {
         store = reader.read();
         if (store != null) {
             System.out.println("######## ------->"+store.getCustPaymentTerm());
             stores.add(store);
         }
     } while (store != null);
}

public Customer(){
    String valueA;
    int custPaymentTerm;
    String valueC;
}

数据文件内容

apple,1,cat
dog,,rat

1 个答案:

答案 0 :(得分:1)

您应该编写自己的FieldSetMapper实现,并将其添加到您的linemapper中,而不是使用Spring提供的BeanWrapperFieldSetMapper。

 lineMapper.setFieldSetMapper(new MyCustomFieldSetMapper());

在该类的mapFieldSet(...)方法中,您可以创建一个包含所有映射字段的新Customer。这可能看起来像这样:

Customer mapFieldSet(FieldSet fs) {
    Customer customer = new Customer();
    customer.setCustPaymentTerm(fs.readInt("custPaymentTerm", 0);
    // set your other fields here
    return customer;
}

如果从行读取空白值,'readInt(...,0)'调用中的零是默认值。