복붙노트

[REDIS] 필드 오류 '필드 오브젝트 대상'의 거부 된 값 []; 코드 [typeMismatch.target., TypeMismatch 예외., typeMismatch.java.util.Date, TypeMismatch 예외]

REDIS

필드 오류 '필드 오브젝트 대상'의 거부 된 값 []; 코드 [typeMismatch.target., TypeMismatch 예외., typeMismatch.java.util.Date, TypeMismatch 예외]

내가 만든 : https://jira.spring.io/browse/BATCH-2778

나는 스프링 배치 + 레디 스 (봄 데이터 레디 스) 예를 개발하고있다. 이 예제에서는 student.csv 파일을 읽고 레디 스 DB에 모든 데이터를 저장하고있다. 나는 날짜로 사용 생년월일 (DateOfBirth)에 원하고 나는 확실히 내가 레디 스에서 값을 저장 날짜에 일부 날짜 로직 변환을 할 필요가 있다고 생각합니다.

내 분석에 따라, 내가 전혀 JSON을 처리하고 있지 않다 때문에 나는, @JsonFormat (모양 = JsonFormat.Shape.STRING, 패턴 = "YYYY-MM-DD")를 사용할 수 습관처럼 보인다. 내가 바이트 [] 등으로 날짜와 날짜에 바이트를 [] 변환 등의 변환기를 이용해야한다고 생각

가리키고 나는이 옵션을 시도했지만 작동하지 않습니다. 어떤 빠른 도움말?

참고 : 나는 문자열 값으로 생년월일 (DateOfBirth)을 저장하지 않습니다.

org.springframework.batch.item.file.FlatFileParseException: Parsing error at line: 2 in resource=[URL [file:c:/Videos/student.csv]], input=[1,John,Doe,05-12-1988 12:34:45]
    at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:184) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:89) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader$$FastClassBySpringCGLIB$$ebb633d0.invoke(<generated>) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:136) ~[spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124) ~[spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.batch.item.file.FlatFileItemReader$$EnhancerBySpringCGLIB$$87932856.read(<generated>) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:157) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:110) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) ~[spring-tx-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:394) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:308) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:141) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:134) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_162]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_162]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_162]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) [spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at com.sun.proxy.$Proxy69.run(Unknown Source) [na:na]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:163) [spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:179) [spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:134) [spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:128) [spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:792) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:776) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at com.myexample.DateBatchPocApplication.main(DateBatchPocApplication.java:12) [classes/:na]
Caused by: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'target' on field 'dateOfBirth': rejected value [05-12-1988 12:34:45]; codes [typeMismatch.target.dateOfBirth,typeMismatch.dateOfBirth,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.dateOfBirth,dateOfBirth]; arguments []; default message [dateOfBirth]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateOfBirth'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateOfBirth': no matching editors or conversion strategy found]
    at org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper.mapFieldSet(BeanWrapperFieldSetMapper.java:200) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.item.file.mapping.DefaultLineMapper.mapLine(DefaultLineMapper.java:43) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:180) ~[spring-batch-infrastructure-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    ... 56 common frames omitted

StudentJob.java

@Configuration
public class StudentJob {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private FlatFileItemReader<Student> studentReader;

    @Autowired
    private StudentWritter studentWritter;

    @Bean
    public Job readstudentCSVFileJob() {
        return jobBuilderFactory.get("readstudentCSVFileJob").incrementer(new RunIdIncrementer())
                .start(countryCurrStepOne()).build();
    }

    @Bean
    public Step countryCurrStepOne() {
        return stepBuilderFactory.get("studentStepOne").<Student, Student>chunk(5).reader(studentReader)
                .writer(studentWritter).build();
    }
}

StudentBatchConfig.java

@Slf4j
@Configuration
public class StudentBatchConfig {
    @Bean(destroyMethod="")
    @StepScope
    public FlatFileItemReader<Student> studentReader(@Value("${input.student.path}") Resource resource) throws IOException {
        log.debug("Resource Path : "+resource.getFile());

        FlatFileItemReader<Student> itemReader = new FlatFileItemReader<>();
        itemReader.setName("STUDENT_READER");
        itemReader.setResource(resource);
        itemReader.setLineMapper(studentlineMapper());
        itemReader.setLinesToSkip(1);
        return itemReader;
    }

    @Bean
    public LineMapper<Student> studentlineMapper() {
        // Delimited Line Tokenizer
        DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
        lineTokenizer.setNames("id", "firstName", "lastName", "dateOfBirth");
        lineTokenizer.setIncludedFields(new int[] {0,1,2,3});

        // Bean Wrapper Field SetMapper
        BeanWrapperFieldSetMapper<Student> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
        fieldSetMapper.setTargetType(Student.class);

        DefaultLineMapper<Student> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizer);
        lineMapper.setFieldSetMapper(fieldSetMapper);
        return lineMapper;
    }

    @Bean
    public StudentWritter studentWritter() {
        return new StudentWritter();
    }
}

StudentWritter.java

public class StudentWritter implements ItemWriter<Student>{
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void write(List<? extends Student> students) throws Exception {
        studentRepository.saveAll(students);
    }
}

편집-1 :

@Slf4j
@Configuration
public class StudentBatchConfig {
    private static final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm");

    @Bean(destroyMethod="")
    @StepScope
    public FlatFileItemReader<Student> countryReader(@Value("${input.student.path}") Resource resource) throws IOException {
        log.debug("Resource Path : "+resource.getFile());

        FlatFileItemReader<Student> itemReader = new FlatFileItemReader<>();
        itemReader.setName("STUDENT_READER");
        itemReader.setResource(resource);
        itemReader.setLineMapper(studentLineMapper());
        itemReader.setLinesToSkip(1);
        return itemReader;
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public LineMapper<Student> studentLineMapper() {
        DefaultLineMapper<Student> lineMapper = new DefaultLineMapper<>();

        // Delimited Line Tokenizer
        DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
        lineTokenizer.setNames("id", "firstName", "lastName", "dateOfBirth");
        lineTokenizer.setIncludedFields(new int[] {0,1,2,3});

        // Date parsing logic has been added
        CustomDateEditor customDateEditor = new CustomDateEditor(format, false);

        HashMap<Class, PropertyEditor> customEditors = new HashMap<>();
        customEditors.put(Date.class, customDateEditor);

        // Bean Wrapper Field SetMapper
        BeanWrapperFieldSetMapper<Student> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
        fieldSetMapper.setTargetType(Student.class);
        fieldSetMapper.setCustomEditors(customEditors);

        lineMapper.setLineTokenizer(lineTokenizer);
        lineMapper.setFieldSetMapper(fieldSetMapper);
        return lineMapper;
    }

    @Bean
    public StudentWritter studentWritter() {
        return new StudentWritter();
    }
}

Student.java

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("student")
public class Student {
    @Id @Indexed
    private String id;
    private String firstName;
    private String lastName;
    private Date dateOfBirth;
}

그러나 날짜는 .. 제대로 저장 문제를 포맷처럼 보인다되지 않습니다 ..

참고 : 나는 마이크로 소프트의 CSV 편집기에서이 파일을 열 경우 그것은 나를 DD-MM-YYYY HH 보여줍니다 mm를

하지만 편집 메모장에서이 파일 ++, 다음이 표시되면

id,firstName,lastName,dateOfBirth
1,John,Doe,25-11-2018 14:48:10
2,Sameer,Kumbhare,25-11-2018 14:48:10

해결법

  1. ==============================

    1.문제는 JSON 관련이 없습니다, 스택 트레이스에 따라 문제가 BeanWrapperFieldSetMapper가 java.util.Date에 1988년 5월 12일 12시 34분 45초를 변환하는 방법을 알고하지 않습니다. 이 같은 사용자 정의 날짜 편집기로 구성해야합니다 :

    문제는 JSON 관련이 없습니다, 스택 트레이스에 따라 문제가 BeanWrapperFieldSetMapper가 java.util.Date에 1988년 5월 12일 12시 34분 45초를 변환하는 방법을 알고하지 않습니다. 이 같은 사용자 정의 날짜 편집기로 구성해야합니다 :

    CustomDateEditor customDateEditor = new CustomDateEditor(/* your DateFormat here */);
    HashMap<Class, PropertyEditor> customEditors = new HashMap<>();
    customEditors.put(Date.class, customDateEditor);
    fieldSetMapper.setCustomEditors(customEditors);
    

    CustomDateEditor가 스프링 프레임 워크에서입니다 : org.springframework.beans.propertyeditors.CustomDateEditor.

    도움이 되었기를 바랍니다.

  2. ==============================

    2.Answrer는 여기에 게시 : https://jira.spring.io/browse/BATCH-2778

    Answrer는 여기에 게시 : https://jira.spring.io/browse/BATCH-2778

    또는

    나는 다음과 같은 것을 사용했다. 레디 스처럼 보인다는 자바 7 날짜 API 제대로 작동하지 않지만, 자바 8 API와 함께 잘 작동합니다. 그러나 동일한에 대한 기본 지원에는 밖에 없다.

    public class StudentFieldSetMapper implements FieldSetMapper<Student>{
    
        @Override
        public Student mapFieldSet(FieldSet fieldSet) throws BindException {
    
            return Student.builder()
                    .id(fieldSet.readString("id"))
                    .firstName(fieldSet.readString("firstName"))
                    .lastName(fieldSet.readString("lastName"))
                    .dateOfBirth(fieldSet.readDate("dateOfBirth", "dd-MM-yyyy HH:mm:ss")).build();
        }
    }
    
  3. from https://stackoverflow.com/questions/53615922/field-error-in-object-target-on-field-rejected-value-codes-typemismat by cc-by-sa and MIT license