Search code examples
grailsgrails-orm

Grails,Gorm, using createCriteria or some other alternative


For example, I've parent class Author:

class Author {    
    String name
    static hasMany = [
         fiction: Book, 
         nonFiction: Book
    ]
}

and a child class Book:

class Book {    
    String title
    static belongsTo = [author: Author]
}

I've done some records to Author using:

def fictBook = new Book(title: "IT")
def nonFictBook = new Book(title: "On Writing: A Memoir of the Craft")
def a = new Author(name: "Stephen King")
             .addToFiction(fictBook)
             .addToNonFiction(nonFictBook)
             .save()

How can I found child-class record by parent and parent-class record by child?

I tried to use findBy method, as below:

def book = Book.get(1)
def author = Author.findByFiction(book)

But I get an error:

Parameter "#2" is not set; SQL statement:

I read, what in some relationship findBy is denied for using, how I can rewrite it using criteria or some others methods?


Solution

  • When you add this belongsTo

    static belongsTo = [author: Author]
    

    this triggers the addition of a property named author of type Author (by an AST transform during compilation), effectively like declaring

    Author author
    

    but don't do that, it'd be redundant.

    So if you have a book, it's Author is accessible via that property:

    def book = Book.get(1)
    def author = book.author