Java Reference
In-Depth Information
If an entity has fields that are loaded lazily, they are normally loaded one at a time as they are ac-
What if there are, say, three fields in an entity that are subject to lazy loading, and if one field is
needed, all of them will be needed? Then it is preferable to load all the lazy fields at once.
That is not possible with standard JPA, but most JPA implementations will allow you to specify a
fetch group to accomplish this. Using fetch groups, it is possible to specify that certain lazily
loaded fields should be loaded as a group whenever one of them is accessed. Typically, multiple
independent groups of fields can be defined; each group will be loaded as needed.
Because it is not a JPA standard, code using fetch groups will be tied to one particular JPA imple-
mentation. But if it is useful, consult your JPA implementation documentation for details.
Note also that the lazy annotation is, in the end, only a hint to the JPA implementation. The
JPA implementation is free to request that the database eagerly provide that data anyway.
On the other hand, perhaps some other data should be preloaded—for example, when one en-
tity is fetched, data for other (related) entities should also be returned. That is known as
eager fetching , and it has a similar annotation:
@OneToMany ( mappedBy = "stock" , fetch = FetchType . EAGER )
private Collection < StockOptionPriceImpl > optionsPrices ;
By default, related entities are already fetched eagerly if the relationship type is @OneToOne
or @ManyToOne (and so it is possible to apply the opposite optimization to them: mark them
as FetchType.LAZY if they are almost never used).
This also is just a hint to the JPA implementation, but it essentially says that any time a stock
price is retrieved, make sure also to retrieve all related option prices. Beware here: a common
expectation about eager relationship fetching is that it will employ a JOIN in the generated
SQL. In typical JPA providers, that is not the case: they will issue a single SQL query to
fetch the primary object, and then one or more SQL commands to fetch any additional, re-
lated objects. From a simple find() method, there is no control over this: if a JOIN state-
ment is required, you will have to use a query and program the JOIN into the query.
Search WWH ::

Custom Search