Java Reference
In-Depth Information
trieval is optimized to serve the needs of the JPA cache, rather than being optimized for
whatever particular request is in progress.
The details of the cache are covered in the next section. For now, let's look at the basic ways
to apply database read optimizations to JPA. JPA reads data from the database in three cases:
when the find() method of the EntityManager is called, when a JPA query is executed, and
when code navigates to a new entity using the relationship of an existing entity. In the stock
class, that latter case means calling the getOptions() method on a Stock entity.
Calling the find() method is the most straightforward case here: only a single row is in-
volved, and (at least) that single row is read from the database. The only thing that can be
controlled here is how much data is retrieved. JPA can retrieve only some of the fields in the
row, it can retrieve the entire row, or it can prefetch other entities are related to the row being
retrieved. Those optimizations apply to queries as well.
There are two possible paths: read less data (because the data won't be needed), or read more
data at a time (because that data will definitely be needed in the future).
Reading less data
To read less data, specify that the field in question is loaded lazily. When an entity is re-
trieved, the fields with a lazy annotation will be excluded from the SQL used to load the
data. If the getter of that field is ever executed, it will mean another trip to the database to re-
trieve that piece of data.
It is rare to use that annotation for simple columns of basic types, but consider using it if the
entity contains large BLOB- or CLOB-based objects.
@Lob
@Column ( name = "IMAGEDATA" )
@Basic ( fetch = FetchType . LAZY )
private
private byte
byte [] imageData ;
In this case, the entity is mapped to a table storing binary image data. The binary data is
large, and the example assumes it shouldn't be loaded unless it is actually needed. Not load-
ing the unneeded data in this case serves two purposes: it makes for faster SQL when the en-
tity is retrieved, and it saves a lot of memory, leading to less GC pressure.
Search WWH ::




Custom Search