Spring Batch 3.0.3:如何为JdbcPagingItemReader查询设置自定义参数?

时间:2015-02-18 23:16:28

标签: java spring spring-batch

将自定义参数设置为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());
    }
}

1 个答案:

答案 0 :(得分:2)

要将作业ExecutionContext中的参数传递给JdbcPagingItemReader,您可以按如下方式配置作者:

<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示例中查看此类配置:https://github.com/spring-projects/spring-batch/tree/master/spring-batch-samples