Java Reference
In-Depth Information
(BLOBs), such as pictures. Unless you're developing a heavily graphics-oriented program
such as an online photo album, it's unlikely that loading a picture as part of an entity used
in a lot of places in the application is a good idea. Because loading BLOB data typically
involves long-running, I/O-heavy operations, they should be loaded cautiously and only as
needed. In general, this optimization strategy is called lazy fetching.
JPA has more than one mechanism to support lazy fetching. Specifying column fetch-mode
using the
@Basic
annotation is the easiest one to understand. For example, you can set the
fetch mode for the
picture
property on the
Item
entity to be lazy as follows:
@Column(name="PICTURE")
@Lob
@Basic(fetch=FetchType.LAZY)
public byte[] getPicture() {
return picture;
}
A
SELECT
statement generated by the
find
method to retrieve
Item
entities won't load
data from the
ITEMS.PICTURE
column into the picture field. Instead, the picture data
will be automatically loaded from the database when the property is first accessed through
the
getPicture
method.
Be advised, however, that lazy fetching is a double-edged sword. Specifying that a column
be lazily fetched means that the
EntityManager
will issue an additional
SELECT
state-
ment just to retrieve the picture data when the lazily loaded field is first accessed. In the ex-
treme case, imagine what would happen if all entity data in an application is lazily loaded.
This would mean that the database would be flooded with a large number of frivolous
SELECT
statements as entity data is accessed. Also, lazy fetching is an optional EJB 3 fea-
ture, which means not every persistence provider is guaranteed to implement it. You should
check your provider's documentation before spending too much time figuring out which
entity columns should be lazily fetched.
Loading related entities
One of the most intricate uses of fetch modes is to control the retrieval of related entities.
Not surprisingly, the
EntityManager'
s
find
method must retrieve all entities related
to the one returned by the method. Let's take the ActionBazaar
Item
entity, an exception-
ally good case because it has a many-to-one, a one-to-many, and two many-to-many rela-
tionships. The only relationship type not represented is one-to-one. The
Item
entity has