当我在Spring Batch中读取CSV文件时,当特定列没有实际值时,它将在行中引发BindException(typeMismatch)。
如何跳过它们?
答案 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..
}
}