4

Are there any scenarios where usage of Hibernate's extra lazy loading can be dangerous?

The documentation says: "Extra-lazy" collection fetching: individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed. It is suitable for large collections.

I'm not sure I understand the implications of this - does it mean I will lose on performance if I declare ALL associations extra lazy, regardless of their size? Is there some kind of rule-of-thumb on the usage of extra lazy loading?

asparagus
  • 416
  • 1
  • 6
  • 9

1 Answers1

5

It's a common N+1 problem, What is SELECT N+1?, multiplied. As of performance, hard to tell: most probably, you'll lose performance. But maybe not.

The problem is, if you try and iterate over an extra-lazy collection, you'll get N+1 query to the database: one for the whole collection, one per entity. It might or might not be good, depending on caching and the nature of your data.

Update: Common sense suggests coding the simplest thing that works (i.e. default settings), then profiling under real-usage scenarios, and deciding on the actual approach after you have data.

There's no real sense in sticking to one particular solution upfront. If you only need one element from collection, extra-lazy retrieval will win. Perhaps. If you need the whole collection, extra-lazy retrieval will impact the performance. That is, if you don't have the whole domain cached, in which case you don't care. Usually.

As of Criteria API and explicit declaration, it sort of undermines the goal of Hibernate: you'd like your business layer not to care (as long as reasonably practicable) about mapping details. So as long as you can keep mapping settings in mappings themselves, it's better to do so. As always, YMMV.

Community
  • 1
  • 1
alf
  • 8,377
  • 24
  • 45
  • What do you think about setting the default to extra lazy and then using using the Criteria API, particularly Criteria.setFetchMode(..), to change fetching strategies in specific cases where all the entities of a collections will be accessed? – asparagus Nov 10 '11 at 09:59
  • OK, thanks for the update. The business layer will not care, I'm just referring to the DAO layer... – asparagus Nov 10 '11 at 11:26
  • There is a case where you should use extra lazy loading upfront: If the collection is relativly huge and you only need a few of the elements. – Jimmy T. Feb 07 '14 at 19:11