////
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
////
[[persistenceBasics-fetching]]
== Fetching

Controlling how and when associated data is loaded is critical for application performance.

See xref:ormdsl-fetchingDSL[Fetching Strategies] for full configuration details.

=== Default: Lazy Loading

Associations are loaded lazily by default — Hibernate does not query associated data until you access it:

[source,groovy]
----
def author = Author.get(1)      // SELECT * FROM author WHERE id=1
author.books.size()             // SELECT * FROM book WHERE author_id=1 (triggered now)
----

=== N+1 Problem

Loading a list of authors and accessing their books triggers one query per author:

[source,groovy]
----
Author.list().each { author ->
    println author.books.size()     // <1>
}
----
<1> N additional queries for N authors — the N+1 problem.

=== Solution: Eager Fetching with Join

[source,groovy]
----
// Option 1: query-time join
def authors = Author.findAll {
    join 'books'
}

// Option 2: mapping-level eager fetch (always eager — use with care)
static mapping = {
    books fetch: 'join'
}
----

=== Batch Fetching

A lighter alternative to `join` — fetch collections in batches to reduce query count without a cartesian product:

[source,groovy]
----
static mapping = {
    books batchSize: 10     // <1>
}
----
<1> Hibernate will initialise up to 10 book collections with a single `IN` query.
