DB 列名称与 CSV 标题名称不同

时间:2021-07-30 12:35:46

标签: spring

我有一个 CSV 文件,其中 CSV 标头和数据库域对象名称不同。如何在 Spring Batch 中获取 CSV 数据并创建模型以持久化到数据库中?

示例,employee.csv

Employee Id, Employee Name, Employee Address, Employee Address 2, Date Of Birth

域对象Employee.java

public string empId;   
public string empName;   
public string empAddress;   
public string empAddress2;   
public string empDOB;

在平面文件阅读器上抛出错误

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;

@Component
@JobScope
public class EmployeeFlatFileItemReader extends FlatFileItemReader<Employee> implements StepExecutionListener {

private String fileName;
private String filePath;

@Override
public void beforeStep(StepExecution stepExecution) {
    fileName = (String) stepExecution.getJobExecution().getJobParameters().getString("fileName");  
    filePath = (String) stepExecution.getJobExecution().getJobParameters().getString("filePath");  
    setResource(new FileSystemResource(filePath));  
}

public EmployeeFlatFileItemReader() {
    try {
        //init();
        DefaultLineMapper<Employee> lineMapper = new DefaultLineMapper<Employee>() {
            {
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames("Employee Id" + "," + "Employee Name" + "," + "Employee Address" + "," + "Employee Address 2" + "," + "Date Of Birth");
                    }
                });
                setFieldSetMapper(new BeanWrapperFieldSetMapper<Employee>() {
                    {
                        setTargetType(Employee.class); // Throws error
                    }
                });
            }
        };
        setLineMapper(lineMapper);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public ExitStatus afterStep(StepExecution stepExecution) {
    return stepExecution.getExitStatus();
}

}

0 个答案:

没有答案
相关问题