Hibernate Performance

N+1 Problem

There is a good description here.

This occurs when we getting the results from a table that is normally joined.
For example
Select * from CARS;
select * from WHEELS where cars = ?;

With the second query, with lazy instantiation, the second query is run for all results in the first query. So if there are n cars returned from the first query we get 1 select from the CARS table and n selects from the WHEELS table resulting in (n+1) selects.

To work around this in Hibernate we need to

1) Use Fetch.EAGER to get all the values rather than when we need them with Fetch.LAZY

2) Use HQL "from WHEELS wheels join fetch wheels.cars cars"

"from WHEELS wheels join fetch wheels.cars cars"

3) Use CRITERIA object

Criteria criteria = session.createCriteria(Cars.class);
criteria.setFetchMode("cars", FetchMode.EAGER);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s