Use @BatchFetch
to read objects related to a relationship mapping (such as @OneToOne
, @OneToMany
, @ManyToMany
, and @ElementCollection
) to be read in a single query.
Annotation Elements
Table 2-3 describes this annotation's elements.
Table 2-3 @BatchFetch Annotation Elements
Annotation Element | Description | Default |
---|---|---|
size |
Default size of the batch fetch, used only when |
|
BatchFetchType |
(optional) The type of batch fetch to use:
|
|
Usage
Batch fetching allows for the optimal loading of a tree. Setting the @BatchFetch
annotation on a child relationship of a tree structure causes EclipseLink to use a single SQL statement for each level. For example, consider an object with an EMPLOYEE
and PHONE
table in which PHONE
has a foreign key to EMPLOYEE
. By default, reading a list of employees' addresses by default requires n queries, for each employee's address. With batch fetching, you use one query for all the addresses.
Using BatchFetchType=EXISTS
does not require an SQL DISTINCT
statement (which may cause issues with LOBs) and may be more efficient for some types of queries or on specific databases.
When using BatchFetchType=IN
, EclipseLink selects only objects not already in the cache. This method may work better with cursors or pagination, or in situations in which you cannot use a JOIN
. On some databases, this may only work for singleton IDs.
Examples
The following examples show how to use this annotation (and XML) with different batch fetch types.
Example 2-7 Using JOIN BatchFetch Type
@OneToOne @BatchFetch(BatchFetchType.JOIN) private Address address;
<one-to-one name="address"> <batch-fetch type="JOIN" /> </one-to-one>
Example 2-8 Using EXISTS BatchFetch Type
@BatchFetch(BatchFetchType.EXISTS) @OneToOne public Map<String, String> getStringMap() { return stringMap; }
<one-to-one name="StringMap"> <batch-fetch type="EXISTS"/> </one-to-one>
Example 2-9 Using IN BatchFetch Type
@BatchFetch(BatchFetchType.IN, size=50) @OneToOne public Map<String, String> getStringMap() { return stringMap; }
<one-to-one name="StringMap"> <batch-fetch type="IN" size="50" /> </one-to-one>
See Also
For more information, see:
Understanding EclipseLink
Solutions Guide for EclispeLink