0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringBatchのItemReaderでDBデータを取得する方法(MyBatis)

Posted at

SpringBatchのChunkモデルを使う場合、データベースからデータを取得し、chunkサイズごとにデータを処理する方法を紹介しようと思います。

サンプルソース

Configuration.java
  @Autowired
  SqlSessionFactory sqlSessionFactory;

  @Bean
  public Step chunk() {
    return stepBuilderFactory.get("chunk").<DemoDto, DemoDto> chunk(100)
        .reader(this.myBatisReader())
        .processor(this.Processor)
        .writer(this.Writer)
        .build();
  }
  
  // MyBatisPagingItemReaderを使ってデータをページ分けて取得
  @Bean
  public MyBatisPagingItemReader<DemoDto> myBatisReader() throws IOException {
    // 検索条件の項目名と値をマップに格納
    Map<String, Object> params = new HashMap<>(); 
    params.put("id", 1);
    return new MyBatisPagingItemReaderBuilder<DemoDto>()
        .sqlSessionFactory(this.sqlSessionFactory) // sqlSessionFactoryは一般的にそのままでいい
        // queryIdは下記Mapperのnamespace+select id
        .queryId("com.example.demo.dao.demoDao.select")
        .parameterValues(params) 
        .pageSize(100) // chunkサイズと合わせる
        .build();
  }
DemoMapper.xml
<mapper namespace="com.example.demo.dao.DemoDao">
  <select id="select" resultMap="BaseResultMap">
	select id, name
	from demo 
    where id = #{id,jdbcType=INTEGER}
    <? limitは必ず記載すること、_pagesizeは上記MyBatisPagingItemReaderBuilderで設置する ?> 
 	limit #{_skiprows}, #{_pagesize}
  </select>
</mapper>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?