CRITICAL
Rule Definition
In a lazy association, the associated object or collection is fetched when it's first accessed. This results in a new request to the database (unless the associated object is cached). This option is almost always used for collection mappings (it should be the default, and we recommend that you consider it as a default for all your collection mappings). Generally, the performance benefits are such that you will want to use lazy instantiation wherever possible (compared with the massive task of reading in all of the entities concerned)
When eager fetching is used, the associated object or collection is fetched together with the owning object, using an SQL outer join, and no further database request is required. But the issue is that it will always be done like this and if the number of row is high, the performance will be affected.
It is more common to specify the use of this strategy (eager fetching) at runtime for a particular HQL or criteria query to avoid that a lazy fetching requires several queries.
Remediation
When the table contains lot of rows, it is better to use a lazy fetching strategy and use a eager strategy at runtime for a particular HQL query, criteria query or JPQL query to avoid that the lazy fetching requires several queries.
Violation Code Sample
<hibernate-mapping >
<class name="A" table ="A">
<id name="id">
<generator class="increment"/>
</id>
// VIOLATION (it could have been lazy = "false")
<set name="b_items" table ="B">
<key column="B_ID"/>
<one-to-many class="B"/>
</array>
</class>
</hibernate-mapping>
Fixed Code Sample
<hibernate-mapping >
<class name="A" table ="A">
<id name="id">
<generator class="increment"/>
</id>
// FIXED
<set name="b_items" lazy="true" table ="B">
<key column="B_ID"/>
<one-to-many class="B"/>
</array>
</class>
</hibernate-mapping>
Reference
Hibernate in Action (ISBN 1932394-15-X) p 148
Related Technologies
JEE
Technical Criterion
Efficiency - SQL and Data Handling Performance
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.