Example & Tutorial understanding programming in easy ways.

Explain the Fetching association in HQL?

Fetching association in HQL: Hibernate uses a fetching strategy to retrieve associated objects if the application needs to navigate the association. Fetch strategies can be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.


Hibernate3 defines the following fetching strategies:


Join fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.


Select fetching:  SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.


Subselect fetching:  SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.


Batch fetching:  An optimization strategy for select fetching. Hibernate retrieves a batch of entity instances or collections in a single SELECT by specifying a list of primary or foreign keys.


Hibernate also distinguishes between:


Immediate fetching:  An association, collection or attribute is fetched immediately when the owner is loaded.


Lazy collection fetching: A collection is fetched when the application invokes an operation upon that collection. This is the default for collections.


"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.


Proxy fetching: A single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.


"No-proxy" Fetching: A single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy; the association is fetched even when only the identifier is accessed. It is also more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.


Lazy attribute fetching: An attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.


We have two orthogonal notions here:  When is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.

Read More →