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.

Answers


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:


Need Your Help

How to Build a RSS reader for Android?

android rss-reader

I am new to android and i am trying to build a RSS reader for Android. I have built all the classes and XML files but its not giving the required output. Its just showing the message

Prawn & Prawnto Rails PDF generation - UTF-8?

ruby-on-rails pdf utf-8 prawn prawnto

I'm using ruby, prawn, and prawnto to dynamically generate pdf's containing text in other languages. I can't seem to get any text in languages with non-english characters to show up. It doesn't thr...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.