본문 바로가기

Spring

[Spring Batch] ItemReader

방식

  • Cursor 방식 : Database에서 데이터를 Streaming
  • Paging 방식 : 페이지 단위로 한번에 데이터를 조회

JdbcCursorItemReader

@Bean
public JdbcCursorItemReader<User> jdbcCursorItemReader() {
    String sql = "SELECT id, name, address FROM User";
    
    return new JdbcCursorItemReaderBuilder<User>()
                   .fetchSize(10)
                   .dataSource(dataSource)  //DataSource DI
                   .rowMapper(new BeanPropertyRowMapper<>(User.class))
                   .sql(sql)
                   .name("jdbcCursorItemReader")
                   .build();
}

JdbcPagingItemReader

@Bean
public JdbcPagingItemReader<User> jdbcPagingItemReader() throws Exception {
    return new JdbcPagingItemReaderBuilder<User>()
                   .pageSize(10)
                   .fetchSize(10)
                   .dataSource(dataSource)  //DataSource DI
                   .rowMapper(new BeanPropertyRowMapper<>(User.class))
                   .queryProvider(createQueryProvider())
                   .name("jdbcPagingItemReader")
                   .build();
}

private PagingQueryProvider createQueryProvider() throws Exception {
    SqlPagingQueryProviderFactoryBean queryProvider = new SqlPagingQueryProviderFactoryBean();
    queryProvider.setDataSource(dataSource);  //DataSource DI
    queryProvider.setSelectClause("id, name, address");
    queryProvider.setFromClause("from User");
    
    Map<String, Order> sortKeys = new HashMap<>(1);
    sortKeys.put("id", Order.ASCENDING);
    
    queryProvider.setSortKeys(sortKeys);
    
    return queryProvider.getObect();
}

RepositoryItemReader

@Bean
public RepositoryItemReader<User> repositoryItemReader() {
    return new RepositoryItemReaderBuilder<User>()
                   .repository(userRepository)  //UserRepository DI
                   .methodName("findByName")
                   .pageSize(10)
                   .arguments(Collections.singletonList("홍길동"))
                   .sort(Collection.singletonMap("id", Sort.Direction.ASC))
                   .name("repositoryItemReader")
                   .build();
}

MongoItemReader

@Bean
public MongoItemReader<User> mongoItemReader() {
    MongoItemReader<User> mongoItemReader = new MongoItemReader<>();
    
    mongoItemReader.setTemplate(mongoTemplate);  //MongoTemplate DI
    mongoItemReader.setCollection("User");
    mongoItemReader.setTargetType(User.class);
    mongoItemReader.setPageSize(10);
    mongoItemReader.setQuery(new Query());
    
    return mongoItemReader;
}

 

 

 

 

참고

https://jojoldu.tistory.com/336

 

 

 

'Spring' 카테고리의 다른 글

[Spring Batch] ItemWriter  (0) 2020.01.09
[Spring Batch] Dynamic Scheduler 다이나믹 스케쥴링  (0) 2020.01.09
[Spring Batch] MongoItemWriter 구현  (0) 2020.01.09
[개념] Spring Batch 란?  (0) 2020.01.08