Karthik Bashyam
Karthik Bashyam

Reputation: 61

Spring Batch JDBCCursorItemReader

Is there any better way to load sql from file system to inject in JDBCCursorItemReader. I want to load sql query from files instead of hardcoding in the configuration file.

//spring bean    
<bean id="jdbcReader" class="com.sample.DatabaseReader">
    <property name="sql" value="query.sql"/>
</bean>

and then i extended JDBCCursorItemReader

//extended cursoritemreader
class DatabaseReader extends JDBCCursorItemReader {

    //Overriden method
    @Override
    public void setSql(String fileName) {
        //file
        File f = new File(fileName);
        //read file from given path
        String query = FileCopyUtils.copyToString(f);
        //pass the query
        super.setSQL(query);

    }
}

Upvotes: 2

Views: 4718

Answers (1)

Michael Minella
Michael Minella

Reputation: 21463

Use Spring's PropertyPlaceHolder to inject the SQL directly into the reader (no need to extend our reader for this). An example would look like this:

 <bean id="jdbcItemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
    <property name="dataSource" ref="dataSource" />
    <property name="rowMapper" ref="myRowMapper>
    <property name="sql" value="${batch.sql}"/>
</bean>

As long as you have a PropertiesPlaceholderConfigurer configured that points to the properties file that holds the batch.sql property, you should be good to go.

Upvotes: 3

Related Questions