spring 批次:typeMismatch.java.sql.Date,类型不匹配

spring batch : typeMismatch.java.sql.Date,typeMismatch

我正在尝试使用 spring 批处理

将此 csv 文件发送到数据库

users.csv

2021-06-22,test1@gmail.com,testFullname1,testMatricule1,1234,testUsername1

2021-06-22,test2@gmail.com,testFullname2,testMatricule2,0000,testUsername2

我有这个错误 无法将类型 'java.lang.String' 的 属性 值转换为 属性

所需的类型 'java.sql.Date'

这里是 batchConfig

package sofrecom.collaborateur.config;

import javax.sql.DataSource;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
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.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import sofrecom.collaborateur.model.DAOUser;



@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    public DataSource dataSource;

    @Bean
    public FlatFileItemReader<DAOUser> reader() {
        FlatFileItemReader<DAOUser> reader = new FlatFileItemReader<DAOUser>();
        reader.setResource(new ClassPathResource("users.csv"));
        reader.setLineMapper(new DefaultLineMapper<DAOUser>() {{
            setLineTokenizer(new DelimitedLineTokenizer() {{
                setNames(new String[] { "dateIntegration","email","fullname","matricule","password","username" });
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<DAOUser>() {{
                setTargetType(DAOUser.class);
            }});
        }});
        return reader;
    }

    @Bean
    public UserItemProcessor processor() {
        return new UserItemProcessor();
    }

    @Bean
    public JdbcBatchItemWriter<DAOUser> writer() {
        JdbcBatchItemWriter<DAOUser> writer = new JdbcBatchItemWriter<DAOUser>();
        writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<DAOUser>());
        writer.setSql("INSERT INTO user ( date_integration,email,fullname,matricule,password,username) VALUES ( :dateIntegration,:email,:fullname,:matricule,:password,:username)");
        writer.setDataSource(dataSource);
        return writer;
    }

    @Bean
    public Job importUserJob(JobCompletionNotificationListener listener) {
        return jobBuilderFactory.get("importUserJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener)
                .flow(step1())
                .end()
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<DAOUser, DAOUser> chunk(10)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }
}

这是用户项目处理器

package sofrecom.collaborateur.config;

import java.sql.Date;
import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

import sofrecom.collaborateur.model.DAOUser;


public class UserItemProcessor implements ItemProcessor<DAOUser, DAOUser> {
    private static final Logger log = LoggerFactory.getLogger(UserItemProcessor.class);
    @Autowired
    private PasswordEncoder bcryptEncoder;

    @Override
    public DAOUser process(final DAOUser person) throws Exception {

        final String password = bcryptEncoder.encode(person.getUsername());
        
        final DAOUser transformedPerson = new DAOUser(person.getDateIntegration(),person.getEmail(),person.getFullname(),person.getMatricule(),password,person.getUsername());

        log.info("Converting (" + person + ") into (" + transformedPerson + ")");

        return transformedPerson;
    }

}

请提供任何解决方案!!

问题是 BeanWrapperFieldSetMapper 默认情况下不知道如何将像 2021-06-22 这样的字符串转换为 java.sql.Date 类型的对象(即字段 dateIntegration) 在你的域对象中 DAOUser。告诉这个映射器如何处理自定义转换的方法是注册一个 ConversionService。此转换服务应注册一个从 Stringjava.sql.Date 的转换器。这是一个简单的例子:

@Bean
public FlatFileItemReader<DAOUser> reader() {
    DefaultConversionService conversionService = new DefaultConversionService();
    conversionService.addConverter(new Converter<String, Date>() { // java.sql.Date
        @Override
        public Date convert(String s) {
            return Date.valueOf(s);
        }
    });
    BeanWrapperFieldSetMapper<DAOUser> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
    fieldSetMapper.setConversionService(conversionService);
    fieldSetMapper.setTargetType(DAOUser.class);

    FlatFileItemReader<DAOUser> reader = new FlatFileItemReader<>();
    reader.setResource(new ClassPathResource("users.csv"));
    reader.setLineMapper(new DefaultLineMapper<DAOUser>() {{
        setLineTokenizer(new DelimitedLineTokenizer() {{
            setNames(new String[] { "dateIntegration","email","fullname","matricule","password","username" });
        }});
        setFieldSetMapper(fieldSetMapper);
    }});
    return reader;
}

您可以根据您在 this repository 中分享的内容找到完整的示例。