Search code examples
grailsgrails-orm

Grails, querying self-referencing table


I have a table with a self-referencing field:

Class Book{

    Integer id
    String name
    Book version
}

When I add books without the "version", the version field is null now I have to query the Book table for records that don't have version (their version field is null), the following code won't work:

def results = Book.withCriteria{
    eq("version", "null")
} 

But I'm getting this exception:

org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of Book.id

what query should i use?


Solution

  • version is a keyword in GORM used for optimistic locking. Modify your domain and the criteria as below to make the criteria return appropriate results.

    //Domain

    class Book {
        Integer id
        String name
        Book bookVersion
    }
    

    //Criteria

    def book = new Book(name: "test", version: null)
    book.id = 1
    book.save(flush: true)
    
    def results = Book.withCriteria{
        isNull("bookVersion")
    }
    
    assert results && results[0] instanceof Book
    

    Also note, bookVersion in the question is of type Book, it cannot be compared to String null.