Thursday, December 17, 2009

Hibernate N+1 Problem

Good article for hibernate users:

http://www.realsolve.co.uk/site/tech/hib-tip-pitfall.php?name=n1selects

Solution

We solve this problem by making sure that the initial query fetches all the data needed to load the objects we need in their appropriately initialized state. One way of doing this is using an HQL fetch join. We use the HQL

"from Manufacturer manufacturer join fetch manufacturer.contact contact"

with the fetch statement. This results in an inner join:

select MANUFACTURER.id from manufacturer and contact ... from
MANUFACTURER inner join CONTACT on MANUFACTURER.CONTACT_ID=CONTACT.id

Using a Criteria query we can get the same result from

Criteria criteria = session.createCriteria(Manufacturer.class);
criteria.setFetchMode("contact", FetchMode.EAGER);

which creates the SQL

select MANUFACTURER.id from MANUFACTURER left outer join CONTACT on
MANUFACTURER.CONTACT_ID=CONTACT.id where 1=1

In both cases, our query returns a list of Manufacturer objects with the contact initialized. Only one query needs to be run to return all the contact and manufacturer information required for the example.

Friday, December 4, 2009

Very nice article regarding the history of scaling major websites.

http://natishalom.typepad.com/nati_shaloms_blog/2008/05/twitter-as-an-e.html