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
Authorentities via aSELECTquery. Further, calling thegetBooks()method of the firstAuthorentity will trigger anotherSELECTquery that initializes the collections of the first threeAuthorentities returned by the previousSELECTquery. This is the effect of@BatchSizeatAuthor's collection-level. -
Second use case fetches all
Bookentities via aSELECTquery. Further, calling thegetAuthor()method of the firstBookentity will trigger anotherSELECTquery that initializes the authors of the first threeBookentities returned by the previousSELECTquery. This is the effect of@BatchSizeatAuthorclass-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:
AuthorandBookare in a lazy relationship (e.g.,@OneToManybidirectional relationship)Authorentity is annotated with@BatchSize(size = 3)Author's collection is annotated with@BatchSize(size = 3)

