Vivid Loading with Many-to-Many Relationship - Grails (GORM)

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

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

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

      

Now that I can do:

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

      

Now I think I can take every author and get the books they are associated with:

authors.each {
   it.books
}

      

Now you will see that it will be recursive (leading to stackoverflow). Does anyone know how this works when it looks like it works?

+2


source to share


2 answers


If it is loaded or lazy loaded, after loading the Hibernate managed instance it is stored in the Hibernate session which is the 1st level cache (if you also set up the 2nd level cache then there will be instances as well and maybe came from there if they were downloaded earlier).

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



The gruesome load of the mapped collection uses the original ResultSet to grab the top level instance plus the child instances in a single database query. Lazy loading of a collection only requires a 2nd database query to populate the collection, but it only takes precedence when loading the collection if needed.

+1


source


For more clarity, you can refer to the blog written by Bert Beckwith at http://burtbeckwith.com/blog/?p=169 and you can also check out the blog link provided.



+1


source







All Articles