Как импортировать из xls в базу данных mysql, используя springbatch? - PullRequest
0 голосов
/ 07 мая 2018

Я пытаюсь создать API, который получает файл .xlsx в качестве входных данных. Данные в файле импортируются в базу данных MySQL. Прошел некоторые уроки. Был в состоянии заставить его работать отлично, когда жестко закодирован путь к файлу и после запуска сервера он успешно выполняется. Но когда я пытаюсь получить файл от пользователя и процесса, я получаю ошибки. Также я не нахожу много ресурсов, чтобы сделать то же самое.

Ниже мой код и ошибки.

@Controller
public class FileController1 {

    @Autowired 
    private JobLauncher jobLauncher;

    @Autowired 
    private Job importUserJob;

    @Autowired 
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired 
    ExcelFileToDatabaseJobConfig excelFileToDatabaseJobConfig;


    @Bean
    ItemReader<StudentDTO> excelStudentReader(@Value("#{jobParameters[fullPathFileName]}") String pathToFile) throws Exception{
        System.out.println("inside excelStudentReader");
        PoiItemReader<StudentDTO> reader = new PoiItemReader<>();
        reader.setLinesToSkip(1);
        reader.setResource(new ClassPathResource(pathToFile));
        //reader.setResource(new UrlResource("file:///D:/joannes/ee.xlsx"));
        reader.setRowMapper(excelRowMapper());
        return reader;
    }
    private RowMapper<StudentDTO> excelRowMapper() {
        System.out.println("inside excelRowMapper");
        BeanWrapperRowMapper<StudentDTO> rowMapper = new BeanWrapperRowMapper<>();
        rowMapper.setTargetType(StudentDTO.class);
        return rowMapper;
    }

    @Bean
    public JdbcBatchItemWriter<StudentDTO> writer(DataSource dataSource) {
        System.out.println("inside writer");
        return new JdbcBatchItemWriterBuilder<StudentDTO>()
                .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
                //.sql("INSERT INTO tbl_item_master (mrp_rate,price,item_code) VALUES (:mrp_rate,:rate,:u_item_code)")
                .sql("update tbl_item_master set mrp_rate=:mrp_rate,price=:rate where item_code=:u_item_code")
                .dataSource(dataSource)
                .build();
    }
    @Bean
    public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
        System.out.println("inside importUserJob");
        return jobBuilderFactory.get("importUserJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener)
                .flow(step1)
                .end()
                .build();
    }
    @Bean
    public Step step1(JdbcBatchItemWriter<StudentDTO> writer,@Qualifier("excelStudentReader") ItemReader<StudentDTO> importReader)throws Exception {
        System.out.println("inside step1");
        return stepBuilderFactory.get("step1")
                .<StudentDTO, StudentDTO> chunk(3000)
                .reader(importReader)
                //.processor(processor())
                .writer(writer)
                .build();
    }

    @RequestMapping(value = "/echofile", method = RequestMethod.POST, produces = {"application/json"})
    //public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
                                    // HttpServletResponse response) throws Exception {
        public @ResponseBody String echoFile(MultipartHttpServletRequest request,
                HttpServletResponse response) throws Exception {

       MultipartFile multipartFile = request.getFile("file");
       /* Long size = multipartFile.getSize();
        String contentType = multipartFile.getContentType();
        InputStream stream = multipartFile.getInputStream();
        byte[] bytes = IOUtils.toByteArray(stream);
        FileUtils.writeByteArrayToFile(new File("D:/joannes/wow.xlsx"), bytes);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("fileoriginalsize", size);
        map.put("contenttype", contentType);
        map.put("base64", new String(Base64Utils.encode(bytes)));
        */

        String path = new ClassPathResource("/").getURL().getPath();//it's assumed you have a folder called tmpuploads in the resources folder
        File fileToImport = new File(path + multipartFile.getOriginalFilename());
        //filePath = fileToImport.getAbsolutePath();
        OutputStream outputStream = new FileOutputStream(fileToImport);
        IOUtils.copy(multipartFile.getInputStream(), outputStream);
        outputStream.flush();
        outputStream.close();
        //Launch the Batch Job
        JobExecution jobExecution = jobLauncher.run(importUserJob,new JobParametersBuilder()
                .addString("fullPathFileName", fileToImport.getAbsolutePath()).toJobParameters());
        //return map;
        return "something";
    }
}

Ошибка:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileController1': Unsatisfied dependency expressed through field 'importUserJob'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'importUserJob' defined in class path resource [com/controller/FileController1.class]: Unsatisfied dependency expressed through method 'importUserJob' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'step1' defined in class path resource [com/controller/FileController1.class]: Unsatisfied dependency expressed through method 'step1' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'excelStudentReader' defined in class path resource [com/controller/FileController1.class]: Unsatisfied dependency expressed through method 'excelStudentReader' parameter 0; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?

Используемые технологии: Springboot, spring-batch-excel, java, mysql, intellij idea, Excel

...