How to Pre-load Entities Using Fetch

This technique is for performance intensive jobs that are doing too many single-row SQL retrieves. The "fetch" command will pre-load the entities, resulting in one fewer database calls.

Write a query using "left join fetch" to select all data. The ORM will fetch the associated collection for every retrieved table into the session cache. Subsequent navigation to the underlying collection is then an in-memory operation with no database IO. Again, PREFER code that performs standard navigation.

  • As a general strategy:
    • For most jobs, navigation is just fine.
    • Write code using navigation first, then ADD the fetch query later, only if it's needed.

This is a link to the Hibernate help on "fetch": http://docs.jboss.org/hibernate/stable/core/reference/en/html_​single/#performance-fetching