I'm using spring batch for file to database processing and currently I'm using PropertyEditors to convert strings in delimited file to some object as provided below.
Map<Class<?>, PropertyEditor> editors = new HashMap<>();
CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
editors.put(Date.class, dateEditor);
So if I have a Date field I am using CustomDateEditor and its successfully parsing the given format date string. However if I have few more date strings in the same file with different formatting, I'm unable to parse them. What I need is to associate the editors to fields, so is there a way I could do that?
If I understand the question correctly, you want two distinct columns to have distinct date formats (not different rows to have different formats). You can do that by implementing a FieldSetMapper, as stated in the docs.
@Bean
public FlatFileItemReader<Person> secondReader() {
FlatFileItemReader<Person> reader = new FlatFileItemReader<Person>();
reader.setResource(new ClassPathResource("sample-data2.csv"));
reader.setLineMapper(new DefaultLineMapper<Person>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setNames(new String[] { "firstName", "lastName", "fDate", "sDate" });
}
});
setFieldSetMapper(new PersonMapper());
}
});
return reader;
}
implementation:
public class PersonMapper implements FieldSetMapper<Person> {
@Override
public Person mapFieldSet(FieldSet fieldSet) throws BindException {
Person person = new Person();
person.setFirstName(fieldSet.readString("firstName"));
person.setLastName(fieldSet.readString("lastName"));
person.setFirstDate(fieldSet.readDate("fDate", "MM/dd/yyyy"));
person.setSecondDate(fieldSet.readDate("sDate", "dd-MMM-yyyy"));
return person;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With