ItemReader
尽管概念简单,ItemReader
却是从多种不同类型输入提供数据的一种方法。最常见的示例包括:
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 describes records with fields of data defined by fixed positions in the file or delimited by some special character (such as a 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
ItemReader
implementations invoke aRowMapper
to return objects, keep track of the current row if restart is required, store basic statistics, and provide some transaction enhancements that are explained later.
还有更多可能性,但我们专注于本章中的基础知识。可以在Appendix A中找到所有可用 `ItemReader`实现的完整列表。
There are many more possibilities, but we focus on the basic ones for this chapter. A
complete list of all available ItemReader
implementations can be found in
Appendix A.
ItemReader
是用于普通输入操作的基本接口,如下面的接口定义所示:
ItemReader
is a basic interface for generic
input operations, as shown in the following interface definition:
public interface ItemReader<T> {
T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException;
}
read
方法定义了 ItemReader
的最基本约定。调用它可返回一个项或(如果没有更多项)返回 null
。一项可以表示文件一行、数据库一行或 XML 文件中的一个元素。通常,这些项会映射到一个可用的域对象(例如 Trade
、Foo
或其他对象),但约定中没有此要求。
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 are mapped to a usable domain object (such as Trade
, Foo
, or others), but there
is no requirement in the contract to do so.
ItemReader
接口的实现有望仅限于前向操作。但是,如果底层资源是事务性的(例如 JMS 队列),则在回滚场景中调用 read
可能会在后续调用中返回相同逻辑项。值得注意的是,ItemReader
没有可处理的项并不会导致引发异常。例如,使用返回 0 个结果的查询配置的数据库 ItemReader
会在第一次调用 read
时返回 null
。
It is expected that implementations of the ItemReader
interface are 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
does not cause an
exception to be thrown. For example, a database ItemReader
that is configured with a
query that returns 0 results returns null
on the first invocation of read
.