[[fetching]]
== Fetching
:sourcedir: ../../../../../test/java/org/hibernate/userguide/fetching

Fetching, essentially, is the process of grabbing data from the database and making it available to the application.
Tuning how an application does fetching is one of the biggest factors in determining how an application will perform.
Fetching too much data, in terms of width (values/columns) and/or depth (results/rows),
adds unnecessary overhead in terms of both JDBC communication and ResultSet processing.
Fetching too little data might cause additional fetching to be needed.
Tuning how an application fetches data presents a great opportunity to influence the application overall performance.

[[fetching-basics]]
=== The basics

The concept of fetching breaks down into two different questions.

* When should the data be fetched? Now? Later?
* How should the data be fetched?

[NOTE]
====
"now" is generally termed eager or immediate. "later" is generally termed lazy or delayed.
====

There are a number of scopes for defining fetching:

_static_::
	Static definition of fetching strategies is done in the mappings.
	The statically-defined fetch strategies is used in the absence of any dynamically defined strategies
    SELECT:::
		Performs a separate SQL select to load the data. This can either be EAGER (the second select is issued immediately) or LAZY (the second select is delayed until the data is needed).
		This is the strategy generally termed N+1.
    JOIN:::
      	Inherently an EAGER style of fetching. The data to be fetched is obtained through the use of an SQL outer join.
    BATCH:::
      	Performs a separate SQL select to load a number of related data items using an IN-restriction as part of the SQL WHERE-clause based on a batch size.
      	Again, this can either be EAGER (the second select is issued immediately) or LAZY (the second select is delayed until the data is needed).
    SUBSELECT:::
      	Performs a separate SQL select to load associated data based on the SQL restriction used to load the owner.
      	Again, this can either be EAGER (the second select is issued immediately) or LAZY (the second select is delayed until the data is needed).
_dynamic_ (sometimes referred to as runtime)::
	Dynamic definition is really use-case centric. There are multiple ways to define dynamic fetching:
    _fetch profiles_::: defined in mappings, but can be enabled/disabled on the `Session`.
    HQL/JPQL::: and both Hibernate and JPA Criteria queries have the ability to specify fetching, specific to said query.
    entity graphs::: Starting in Hibernate 4.2 (JPA 2.1) this is also an option.

[[fetching-strategies]]
=== Applying fetch strategies

Let's consider these topics as it relates to an simple domain model and a few use cases.

[[fetching-strategies-domain-model-example]]
.Sample domain model
====
[source, JAVA, indent=0]
----
include::{sourcedir}/FetchingTest.java[tags=fetching-strategies-domain-model-example]
----
====

[IMPORTANT]
====
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. 
This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. 
Hibernate, as a JPA provider, honors that default.
====

[[fetching-strategies-no-fetching]]
=== No fetching

For the first use case, consider the application login process for an `Employee`.
Let's assume that login only requires access to the `Employee` information, not `Project` nor `Department` information.

[[fetching-strategies-no-fetching-example]]
.No fetching example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/FetchingTest.java[tags=fetching-strategies-no-fetching-example]
----
====

In this example, the application gets the `Employee` data.
However, because all associations from `Employee `are declared as LAZY (JPA defines the default for collections as LAZY) no other data is fetched.

If the login process does not need access to the `Employee` information specifically, another fetching optimization here would be to limit the width of the query results.

[[fetching-strategies-no-fetching-scalar-example]]
.No fetching (scalar) example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/FetchingTest.java[tags=fetching-strategies-no-fetching-scalar-example]
----
====

[[fetching-strategies-dynamic-fetching]]
=== Dynamic fetching via queries

For the second use case, consider a screen displaying the `Projects` for an `Employee`.
Certainly access to the `Employee `is needed, as is the collection of `Projects` for that Employee. Information about `Departments`, other `Employees` or other `Projects` is not needed.

[[fetching-strategies-dynamic-fetching-jpql-example]]
.Dynamic JPQL fetching example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/FetchingTest.java[tags=fetching-strategies-dynamic-fetching-jpql-example]
----
====

[[fetching-strategies-dynamic-fetching-criteria-example]]
.Dynamic query fetching example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/FetchingTest.java[tags=fetching-strategies-dynamic-fetching-criteria-example]
----
====

In this example we have an `Employee `and their `Projects` loaded in a single query shown both as an HQL query and a JPA Criteria query.
In both cases, this resolves to exactly one database query to get all that information.

[[fetching-strategies-dynamic-fetching-entity-graph]]
=== Dynamic fetching via JPA entity graph

JPA 2.1 introduced entity graphs so the application developer has more control over fetch plans.

[[fetching-strategies-dynamic-fetching-entity-graph-example]]
.Fetch graph example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/GraphFetchingTest.java[tags=fetching-strategies-dynamic-fetching-entity-graph-mapping-example]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/GraphFetchingTest.java[tags=fetching-strategies-dynamic-fetching-entity-graph-example]
----
====

[NOTE]
====
Entity graphs are the way to override the EAGER fetching associations at runtime.
With JPQL, if an EAGER association is omitted, Hibernate will issue a secondary select for every association needed to be fetched eagerly.
====

[[fetching-strategies-dynamic-fetching-profile]]
=== Dynamic fetching via Hibernate profiles

Suppose we wanted to leverage loading by natural-id to obtain the `Employee` information in the "projects for and employee" use-case.
Loading by natural-id uses the statically defined fetching strategies, but does not expose a means to define load-specific fetching.
So we would leverage a fetch profile.

[[fetching-strategies-dynamic-fetching-profile-example]]
.Fetch profile example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/ProfileFetchingTest.java[tags=fetching-strategies-dynamic-fetching-profile-mapping-example]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/ProfileFetchingTest.java[tags=fetching-strategies-dynamic-fetching-profile-example]
----
====

Here the `Employee` is obtained by natural-id lookup and the Employee's `Project` data is fetched eagerly.
If the `Employee` data is resolved from cache, the `Project` data is resolved on its own.
However, if the `Employee` data is not resolved in cache, the `Employee` and `Project` data is resolved in one SQL query via join as we saw above.