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

Long type 64bit linux

c linux bit-manipulation

Very simple questions guys, but maybe I'm just forgetting something.

SQL Server 2008: how to format the output as a currency

sql sql-server formatting

I have a query string which returns a value that has several decimal places. I want to format this to a currency $123.45.

maven multi-module assembly

maven-2 maven-assembly-plugin multi-module

I have a multi-module maven project, and I'm trying to create an assembly for the project. The assembly should be a zip file, including all of the jars from the dependent projects as well as all of...

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.