Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeanWrapperFieldsetMapper mapping PropertyEditor per field basis

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?

like image 379
dShringi Avatar asked Jun 16 '15 09:06

dShringi


1 Answers

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;
}

}

like image 75
Sergio Avatar answered Oct 17 '22 00:10

Sergio