List<Author> authors = authorRepository.findAll();
for (Author author : authors) {
System.out.println(author.getBooks().size());
}The initial findAll() triggers 1 query to load all authors. Then, accessing each author's books triggers 1 query per author due to lazy loading, totaling 5 more queries. So, 6 queries in total.
JOIN FETCH tells JPA to load the association eagerly in the same query, preventing multiple queries.
If the transaction ends before accessing the collection, lazy loading triggers separate queries outside the transaction, causing N+1.
Lazy loading defers loading related entities until accessed, causing one query per related entity, leading to N+1 queries.
The first query loads all authors (1 query). Batch fetching loads books in batches of 5 authors, so 10 authors require 2 batches (2 queries). Total queries = 3.
