JPA OneToMany and Getting children with a single query
I notice that in hibernate, it queries the child collections of entities an entity at a time. So, for example, I have a Person entity with a OneToMany relationship with PhoneNumber as well as a OneToMany relationship with EmailAddress. If I do a simple query on the Person entity that returns 1,000 people then hibernate will make 1,000 queries to EmailAddress and 1,000 queries to PhoneNumber. Let's forget about eager or lazy fetching for a minute and assume I will be accessing the phone and email collections of every person.
This seems like a naive implementation. Is there a simple way to change this so there is only 1 query into PhoneNumber and only 1 query into EmailAddress? These should be put into a map keyed by their Person foreign key so they are easily retrieved by the Person getter methods.
Any thoughts besides doing a brute force query into the session cache for emails and phone numbers BEFORE executing the Person query?
TIA, let me know if you need additional data.
Apart for doing the queries by yourself, you could simply enable batch fetching, as described in the documentation:
You can also enable batch fetching of collections. For example, if each Person has a lazy collection of Cats, and 10 persons are currently loaded in the Session, iterating through all persons will generate 10 SELECTs, one for every call to getCats(). If you enable batch fetching for the cats collection in the mapping of Person, Hibernate can pre-fetch collections: