Search code examples
javaspringspring-bootspring-batchbatch-processing

Spring Boot Batch Processing - Adding a new column


I try to implement an example of Spring Boot Batch Processing (CSV to h2 database). I want to add a new column named "age" to calculate a year according to birthdate. How can I define "age" column in lineMapper? I try to use public class UserProcessor implements ItemProcessor<UserDTO, User> return User DTO (id,person_id,first_name,last_name,email,gender,country,date, age)

Here is the sample csv file shown below.

id,person_id,first_name,last_name,email,gender,country,date
1,38c324d5-2d8f-4687-8862-30f15a19f26c,Melesa,Conquest,mconquest0@goodreads.com,Female,Poland,2022-09-13 09:13:05
2,082f0eff-e1ca-4f6e-8348-247b6a676547,Dodi,Jachtym,djachtym1@github.com,Polygender,Armenia,2022-03-02 09:26:13

I already defined date shown below in User Entity.

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime date;

I try to calculate age with this method shown below

public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
        if ((birthDate != null) && (currentDate != null)) {
            return Period.between(birthDate, currentDate).getYears();
        } else {
            return 0;
        }
}

I want to get a table shown below in h2 database.

id,person_id,first_name,last_name,email,gender,country,date,age
    1,38c324d5-2d8f-4687-8862-30f15a19f26c,Melesa,Conquest,mconquest0@goodreads.com,Female,Poland,2000-09-13 09:13:05,22

How can I do that?


Solution

  • LineMapper is not the place where data should be processed. The line mapper should only be used to map a single line from the input file to an instance of the domain object.

    Such calculations or data transformations are typically done in an item processor where items are amended/enriched with additional data. Please check the Item processing section of the reference documentation for more details about this matter.

    Once items are processed, the writer can select the new column and persist it in the database.