Spring Batch How to read multiple table (queries) as Reader and write it as flat file write

戏子无情 提交于 2021-02-07 17:23:19

问题


In my project I have read multiple tables with different queries and consolidate those results sets in flat files. How do I achieve that. I mean JdbcReader is directly taking 1 select query, how can I customize it.


回答1:


If JdbcCursorItemReader does not suit your needs, you are always free to implement a custom reader by implementing the ItemReader interface.

public interface ItemReader<T> {
        T read() throws Exception, UnexpectedInputException, ParseException;
}

Just write a class that implements this interface and inject a jdbcTemplate to query multiple tables.

public Class MyCompositeJdbcReader implements ItemReader<ConsolidateResult>{
    private JdbcTemplate jdbcTemplate;

    public ConsolidateResult read() 
       throws Exception, UnexpectedInputException, ParseException{
    ConsolidateResult cr = new ConsolidateResult();     

    String name= this.jdbcTemplate.queryForObject(
        "select name from customer where id = ?",new Object[]{1}, String.class);
    String phoneNumber= this.jdbcTemplate.queryForObject(
        "select phone from customer_contact where custid = ?",
        new Object[]{1},String.class);

    cr.setName(name);
    cr.setPhone(phoneNumber);
    return cr;
 }

}

I did not compile the code but I hope it gives an idea.



来源:https://stackoverflow.com/questions/11476531/spring-batch-how-to-read-multiple-table-queries-as-reader-and-write-it-as-flat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!