Fetching Associations In Batches Via @BatchSize
Description: This application uses Hibernate specific @BatchSize
at class/entity-level and collection-level. Consider Author
and Book
entities invovled in a bidirectional-lazy @OneToMany
association.
-
First use case fetches all
Author
entities via aSELECT
query. Further, calling thegetBooks()
method of the firstAuthor
entity will trigger anotherSELECT
query that initializes the collections of the first threeAuthor
entities returned by the previousSELECT
query. This is the effect of@BatchSize
atAuthor
's collection-level. -
Second use case fetches all
Book
entities via aSELECT
query. Further, calling thegetAuthor()
method of the firstBook
entity will trigger anotherSELECT
query that initializes the authors of the first threeBook
entities returned by the previousSELECT
query. This is the effect of@BatchSize
atAuthor
class-level.
Note: Fetching associated collections in the same query with their parent can be done via JOIN FETCH
or entity graphs as well. Fetching children with their parents in the same query can be done via JOIN FETCH
, entity graphs and JOIN
as well.
Key points:
Author
andBook
are in a lazy relationship (e.g.,@OneToMany
bidirectional relationship)Author
entity is annotated with@BatchSize(size = 3)
Author
's collection is annotated with@BatchSize(size = 3)