如何在FlatFileItemReader <t>中为空的情况下跳过特定列的值?

时间:2018-07-02 09:41:06

标签: java spring mongodb spring-mvc spring-batch

当我在Spring Batch中读取CSV文件时,当特定列没有实际值时,它将在行中引发BindException(typeMismatch)。

如何跳过它们?

1 个答案:

答案 0 :(得分:0)

我按照以下步骤配置了ItemReader:

Spring Config:

@Bean
Step step1() {
    return stepBuilderFactory.get("step1")
            .listener(dataProcessor)
            .chunk(100)
            .faultTolerant()
            .reader(yourReader()).faultTolerant().skipPolicy(new ItemVerificationSkipper())
            .processor(dataProcessor)
            .writer(writer())
            .build();
}

重要的部分是添加一个skipPolicy:

reader(yourReader()).faultTolerant().skipPolicy(new ItemVerificationSkipper())

ItemVerificationSkipper.java

@Slf4j
public class ItemVerificationSkipper implements SkipPolicy {

    @Override
    public boolean shouldSkip(Throwable exception, int skipCount) throws SkipLimitExceededException {

            StringBuilder errorMessage = new StringBuilder();
            errorMessage
                    .append("Unexpected exception ")
                    .append(exception.toString())
//                    .append(ExceptionUtils.getStackFrames(exception))
                    .append("\n");
            log.error("{}", errorMessage.toString());
            return true;
    }

}

在进一步评论后编辑:

跳过列值所需的RowMapper实现:

配置:

itemReader.setRowMapper(new CustomRowMapper());

CustomRowMapper.java

public class CustomRowMapper implements RowMapper<YourClass> {

    @Override
    public YourClass mapRow(ResultSet rs, int rowNum) throws SQLException {
        String columnXYZ = rs.getString("yourColumnName");
        //check input etc..

    }
}