Langali
Langali

Reputation: 3207

Eager Loading with Many-to-Many relationship - Grails (GORM)

Each book can have many authors. And each author can author many books.

class Book {
   static belongsTo = Author
   static hasMany = [authors:Author]
}

class Author {
   static hasMany = [books:Book]
}

Now when can I do:

def book = Book.get(id)
def authors = book.authors

Now I am thinking I should be able to take each author and get the books he is associated with:

authors.each {
   it.books
}

You see now it would get recursive (leading to stackoverflow). Does anyone know how it exactly works, when it is doing eager fetch?

Upvotes: 2

Views: 2097

Answers (2)

Amit Jain
Amit Jain

Reputation: 1382

For more clarity you can refer to the blog written by Burt Beckwith at http://burtbeckwith.com/blog/?p=169 and you can also go through the presentation link given in the blog.

Upvotes: 1

Burt Beckwith
Burt Beckwith

Reputation: 75671

Whether it's eagerly or lazily loaded, once a Hibernate-managed instance is loaded it's kept in the Hibernate Session, which is its 1st-level cache (if you've also configured a 2nd-level cache then instances will also be there and may have come from there if they were previously loaded).

So having loaded the book, and then having loaded its author collection (a Set by default), each author's book is already in the Session, so there's no need to go to the database.

Eagerly loading a mapped collection uses the initial ResultSet to grab the top-level instance plus the child instances in one database query. Lazily loading the collection just requires a 2nd database query to populate the collection but it has the benefit of only loading the collection if needed.

Upvotes: 1

Related Questions