Reputation: 167
I'm getting a groovy.lang.MissingPropertyException every time I'm trying to pass a variable to a where query.
These are my domain classes:
class Book {
String title
static belongsTo = [author: Author]
static constraints = {
title(blank: false, maxSize: 100)
}
}
class Author {
String name
static hasMany = [books: Book]
static constraints = {
name(unique: true, blank: false, maxSize: 50)
}
}
And this the test method that raises the exception:
@Test
void testWhereQuery() {
long authorId = 5
def query = Book.where {
author.id == authorId
}
def books = query.list()
assert books.size() == 0
}
groovy.lang.MissingPropertyException: No such property: authorId for class: grails.gorm.DetachedCriteria
at grails.gorm.DetachedCriteria.methodMissing(DetachedCriteria.groovy:808)
at grails.gorm.DetachedCriteria.build(DetachedCriteria.groovy:723)
at org.grails.datastore.gorm.GormStaticApi.where(GormStaticApi.groovy:116)
at helloworld.BooksIntegrationTests.testWhereQuery(BooksIntegrationTests.groovy:38)
How can I pass a variable to the query?
Upvotes: 3
Views: 1809
Reputation: 21
I have also been battling with this.
Try changing your where query to:
def query = Book.where {
author.id.toString() == "${authorId}"
}
This nasty technique only works inside strings and is the only way I have been able to get variable substitution to work in where queries.
The lack of decent support for parameterized where queries makes them next to useless, IMO. Shame, because the format of the notation is very concise.
Upvotes: 2
Reputation: 1882
I asked this question myself and came to discover that where queries don't appear to offer any support for variables. Only named queries seem to be capable of doing that.
Parameters with new where queries in Grails 2.0
Upvotes: 1