How to create a custom item reader in spring package

In my application, I use sqlProcessor as the database: https://github.com/hudec/sql-processor/wiki .

so when I want to read a list of objects, I call:

List<MyClass> myClassList = myClassDao.list(...) 

How should I iterate over this list in itemReader or how should I create my custom item reader that reads data from a database using sqlProcessor

+4
source share
4 answers

Use ItemReaderAdapter .
From Javadok:
Invokes a custom method on a delegate plain old Java object which itself provides an item.

 <bean id="itemReader" class="org.springframework.batch.item.adapter.ItemReaderAdapter"> <property name="targetObject" ref="myClassDao" /> <property name="targetMethod" value="list" /> <property name="arguments"> <list> <!-- add arguments list --> </list> </property> </bean> <bean id="myClassDao" class="path.to.MyClassDAO" / 

If you have special conditions, arguments, or other needs, you can create your own ItemReader, but you can extend the ItemReaderAdapter to reuse the DAO and save time.

+5
source

You just need to implement the ItemReader interface. For instance:

 public MyReader implements ItemReader<YourClass> { @Override public YourClass read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { // Implement your read logic, return null when no more items } } 

this simple class will return your data and just stop reading when all the request data is received,

I hope this helps you or other users :)

+4
source

If you already have a list, you can simply instantiate IteratorItemReader .

 List<MyClass> myClassList = myClassDao.list(...) ItemReader reader = new IteratorItemReader(myClassList); 
+1
source

Take a look at ListItemReader

0
source

Source: https://habr.com/ru/post/1498361/


All Articles