Example usage for org.springframework.batch.item.database PagingQueryProvider init

List of usage examples for org.springframework.batch.item.database PagingQueryProvider init

Introduction

In this page you can find the example usage for org.springframework.batch.item.database PagingQueryProvider init.

Prototype

void init(DataSource dataSource) throws Exception;

Source Link

Document

Initialize the query provider using the provided DataSource if necessary.

Usage

From source file:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java

@Test
public void testWithFactory() throws Exception {
    // setup queryProviderFactory
    SqlPagingQueryProviderFactoryBean factory = new SqlPagingQueryProviderFactoryBean();
    factory.setDataSource(dataSource);//from   w  w w.ja  v  a2  s  .co  m
    factory.setDatabaseType("HSQL");
    factory.setSelectClause("select ID, NAME");
    factory.setFromClause("from TEST");
    factory.setWhereClause("where NAME <> 'foo'");
    factory.setSortKey("ID");
    PagingQueryProvider queryProvider = (PagingQueryProvider) factory.getObject();
    // call init to imitate spring context startup behaviour        
    queryProvider.init(dataSource);

    // setup reader
    JdbcPagingItemReader<String> reader = new JdbcPagingItemReader<String>();
    reader.setDataSource(dataSource);
    reader.setQueryProvider(queryProvider);
    reader.setRowMapper(new ParameterizedRowMapper<String>() {

        @Override
        public String mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getString("NAME");
        }
    });
    reader.setPageSize(2);

    // needed call, normally done at spring application context startup
    reader.afterPropertiesSet();

    reader.open(MetaDataInstanceFactory.createStepExecution().getExecutionContext());
    // read
    try {
        int count = 0;
        String line;
        while ((line = reader.read()) != null) {
            assertEquals(String.valueOf(count), line);
            count++;
        }
        assertEquals(EXPECTED_COUNT, count);
    } catch (Exception e) {
        throw e;
    } finally {
        reader.close();
    }
}