Java Persistence API (JPA) Extensions Reference for EclipseLink, Release 2.5
  Go To Table Of Contents
 Search
 PDFComments
Comments


@BatchFetch

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=IN to define the number of keys in each IN clause

256 or the query's pageSize (for cursor queries)

BatchFetchType

(optional) The type of batch fetch to use:

  • JOIN – The original query's selection criteria is joined with the batch query

  • EXISTS – Uses an SQL EXISTS clause and a sub-select in the batch query instead of a JOIN

  • IN – Uses an SQL IN clause in the batch query, passing in the source object IDs.

JOIN



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: