2

model:

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

class Book{
  String name
  Author author

  static belongsTo = Author
}

Then i have a controller

class MyController{
  def authors{
     def authors = Author.getAll()
     render authors as JSON
  }

The problem is that even if the association Author-Books is lazy, N+1 queries are executed to fetch eagerly the books for each Author. What does it happen and how can i disable it

user711189
  • 4,383
  • 4
  • 30
  • 48

1 Answers1

5

You are using default JSON converter, which tries to convert all fields of your model. Thats why it is doing all those selects.

You should implement your own JSON converter for you model which would not ask DB for books. You can do it in BootStrap like this:

import grails.converters.JSON
class BootStrap {
    def init = {servletContext ->
        JSON.registerObjectMarshaller(Author) {
            def returnArray = [:]
            returnArray['name'] = it.name
            return returnArray
    }

}

kenota
  • 5,640
  • 1
  • 15
  • 11