All batch processing can be described in its most simple form as
reading in large amounts of data, performing some type of calculation or
transformation, and writing the result out. Spring Batch provides three key
interfaces to help perform bulk reading and writing:
ItemReader, ItemProcessor and
ItemWriter.
Although a simple concept, an ItemReader is
the means for providing data from many different types of input. The most
general examples include:
Flat File- Flat File Item Readers read lines of data from a flat file that typically describe records with fields of data defined by fixed positions in the file or delimited by some special character (e.g. Comma).
XML - XML ItemReaders process XML independently of technologies used for parsing, mapping and validating objects. Input data allows for the validation of an XML file against an XSD schema.
Database - A database resource is accessed to return
resultsets which can be mapped to objects for processing. The
default SQL ItemReaders invoke a RowMapper to
return objects, keep track of the current row if restart is
required, store basic statistics, and provide some transaction
enhancements that will be explained later.
There are many more possibilities, but we'll focus on the basic ones for this chapter. A complete list of all available ItemReaders can be found in Appendix A.
ItemReader is a basic interface for generic
input operations:
public interface ItemReader<T> {
T read() throws Exception, UnexpectedInputException, ParseException;
}The read method defines the most essential
contract of the ItemReader; calling it returns one
Item or null if no more items are left. An item might represent a line in
a file, a row in a database, or an element in an XML file. It is generally
expected that these will be mapped to a usable domain object (i.e. Trade,
Foo, etc) but there is no requirement in the contract to do so.
It is expected that implementations of the
ItemReader interface will be forward only. However,
if the underlying resource is transactional (such as a JMS queue) then
calling read may return the same logical item on subsequent calls in a
rollback scenario. It is also worth noting that a lack of items to process
by an ItemReader will not cause an exception to be
thrown. For example, a database ItemReader that is
configured with a query that returns 0 results will simply return null on
the first invocation of read.