将自定义参数设置为JdbcPagingItemReader查询的最佳方法是什么?

我的自定义JdbcPagingItemReader实现:

public class CustomItemReader extends JdbcPagingItemReader<Long> {
    public CustomItemReader(DataSource dataSource) throws Exception {
        SqlPagingQueryProviderFactoryBean queryProvider = new SqlPagingQueryProviderFactoryBean();
        queryProvider.setDataSource(dataSource);
        queryProvider.setSelectClause("SELECT t1.id");
        queryProvider.setFromClause("FROM table1 t1 LEFT JOIN table2 t2 ON t2.fk_table1_id = t1.id");
        queryProvider.setWhereClause("WHERE (t1.col1 = :param1) AND ((t2.id IS NULL) OR (t2.col3 = :param2))");
        queryProvider.setSortKey("t1.id");

        setDataSource(dataSource);
        setFetchSize(10);
        setRowMapper(new RowMapper<Long>() {
            @Override
            public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getLong(1);
            }
        });
        setQueryProvider(queryProvider.getObject());
    }
}

最佳答案

要将参数从作业的ExecutionContext传递到JdbcPagingItemReader,您可以按以下方式配置writer:

<bean id="itemReader" class="org.springframework.batch.item.database.JdbcPagingItemReader" scope="step">
    <property name="dataSource" ref="dataSource" />
    <property name="rowMapper">
        <bean class="MyRowMapper" />
    </property>
    <property name="queryProvider">
        <bean class="org.springframework.batch.item.database.support.SqlPagingQueryProviderFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="sortKeys">
                <map>
                    <entry key="t1.id" value="ASCENDING"/>
                </map>
            </property>
            <property name="selectClause" value="SELECT t1.id" />
            <property name="fromClause" value="FROM table1 t1 LEFT JOIN table2 t2 ON t2.fk_table1_id = t1.id" />
            <property name="whereClause" value=""WHERE (t1.col1 = :param1) AND ((t2.id IS NULL) OR (t2.col3 = :param2))" />
        </bean>
    </property>
    <property name="pageSize" value="10" />
    <property name="parameterValues">
        <map>
            <entry key="param1" value="#{jobExecutionContext[param1]}" />
            <entry key="param2" value="#{jobExecutionContext[param2]}" />
        </map>
    </property>
</bean>


您可以在此处的Spring Batch示例中查看这样的配置:

09-26 11:28