You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: documentation/src/main/asciidoc/introduction/Interacting.adoc
+66Lines changed: 66 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -337,6 +337,72 @@ We're getting a bit ahead of ourselves here, but let's quickly mention the gener
337
337
Instead, fetch all the data you'll need upfront at the beginning of a unit of work, using one of the techniques described in <<association-fetching>>, usually, using _join fetch_ in HQL.
338
338
====
339
339
340
+
It's clear we need a way to request that an association be _eagerly_ fetched using a database `join`.
341
+
One way to do that is by passing an `EntityGraph` to `find()`.
342
+
343
+
[[entity-graph]]
344
+
=== Entity graphs and eager fetching
345
+
346
+
When an association is mapped `fetch=LAZY`, it won't, by default, be fetched when we call the `find()` method.
347
+
We may request that an association be fetched eagerly (immediately) by passing an `EntityGraph` to `find()`.
348
+
349
+
The JPA-standard API for this is a bit unwieldy:
350
+
351
+
[source,java]
352
+
----
353
+
var graph = entityManager.createEntityGraph(Book.class);
This results in a SQL query with _four_ ``left outer join``s.
382
+
383
+
[NOTE]
384
+
====
385
+
In the code examples above, we're making use of the JPA static metamodel.
386
+
The classes `Book_` and `Author_` are generated by the annotation processor we have in our <<hello-hibernate,gradle build>>, one of the <<optional-dependencies,optional dependencies>> of Hibernate.
387
+
They let us refer to attributes of our model in a completely type-safe way.
388
+
We'll use them again, below, when we talk about <<criteria-queries>>.
389
+
====
390
+
391
+
JPA specifies that any given `EntityGraph` may be interpreted in two different ways.
392
+
393
+
- A _fetch graph_ specifies exactly the associations that should be eagerly loaded.
394
+
Any association not belonging to the entity graph is proxied and loaded lazily only if required.
395
+
- A _load graph_ specifies that the associations in the entity graph are to be fetched in addition to the associations mapped `fetch=EAGER`.
396
+
397
+
You're right, the names make no sense.
398
+
But don't worry, if you take our advice, and map your associations `fetch=LAZY`, there's no difference between a "fetch" graph and a "load" graph, so the names don't matter.
399
+
400
+
[NOTE]
401
+
====
402
+
JPA even specifies a way to define named entity graphs using annotations.
403
+
But the annotation-based API is so verbose that it's just not worth using.
0 commit comments