首页 > 解决方案 > JdbcCursorItemReader 是否必须关闭连接?

问题描述

Spring Batch 文档中有一个示例(https://docs.spring.io/spring-batch/docs/4.2.x/reference/html/readersAndWriters.html#cursorBasedItemReaders

public ItemReader<RevertedBillCredit> verifyCreditReader() {     
        JdbcCursorItemReader itemReader = new JdbcCursorItemReader();
        itemReader.setDataSource(dataSource);
        itemReader.setSql("SELECT ID, NAME, CREDIT from CUSTOMER");
        itemReader.setRowMapper(new CustomerCreditRowMapper());
        int counter = 0;
        ExecutionContext executionContext = new ExecutionContext();
        itemReader.open(executionContext);
        Object customerCredit = new Object();
        while(customerCredit != null){
            customerCredit = itemReader.read();
            counter++;
        }
        itemReader.close();
    }

我发现有些文档说 JdbcCursorItemReader 会在查询后自动关闭连接。但是,为什么我们需要 itemReader.close() 呢?JdbcCursorItemReader 是否必须手动关闭连接?

标签: springspring-batch

解决方案


The snippet from reference docs you linked explains how things work behind the scene, but when the reader is used in a chunk-oriented step, you don't need to call open/close methods yourself, Spring Batch will do it. So your item reader bean definition should be something like:

public ItemReader<RevertedBillCredit> verifyCreditReader() {     
    JdbcCursorItemReader itemReader = new JdbcCursorItemReader();
    itemReader.setDataSource(dataSource);
    itemReader.setSql("SELECT ID, NAME, CREDIT from CUSTOMER");
    itemReader.setRowMapper(new CustomerCreditRowMapper());
    return itemReader;
}

推荐阅读