0

After reading this article enter link description here

I got the idea that a fetch mode = LAZY will always result in N +1 problem. IS this true? If so ,why? OpenJPA/Hibernate should be able to optimize the query even if fetch type is LAZY. No?

Victor
  • 16,609
  • 71
  • 229
  • 409

2 Answers2

0

You can specify eager fetch in query to avoid it. This produces a JOIN sql.

Criteria c = session.createCriteria(Entity1.class);
c.setFetchMode("anotherObj", FetchMode.JOIN)
return c.list();
Yugang Zhou
  • 7,123
  • 6
  • 32
  • 60
  • My question is not how to avoid N +! by an eager fetch, but...does a LAZY fetch automatically mean a N +1 select? – Victor Jul 30 '13 at 14:30
0

Yes, it will. But the extra SELECTs are executed only when you access the objects defined in a relationship (that's why it is called LAZY load).

This is an excellent article that explains it in more details: http://www.mkyong.com/hibernate/hibernate-fetching-strategies-examples/

Cheers

Rafa
  • 1,997
  • 3
  • 21
  • 33