After encountering some shortcomings of named queries I decided to try out Grails' where queries, mainly for their more powerful composition capabilities.
The results were surprising. For the following domain class..
class Bike {
Operator operator
static forOperator(Operator op) {
Bike.where { operator == op }
}
static firstOperator = where { operator.id == 1 }
}
..I call this code:
def op = Operator.get(1)
//try to get bike 1 with the additional safety that we won't get it unless it's from operator 1
def q1 = Bike.where { operator == op }.where { id == 1 }.size()
def q2 = Bike.forOperator(op).where { id == 1 }.size()
def q3 = Bike.firstOperator.where { id == 1 }.size()
println q1
println q2
println q3
//prints out
// 1
// 6
// 1
At first look it seems the second call isn't behaving properly, but logging the generated SQL shows that only the first call is actually doing what I expect it to do:
These queries are actually run:
select count(*) as y0_ from bike this_ where this_.operator_id=? and this_.id=?
select count(*) as y0_ from bike this_ where this_.operator_id=?
select count(*) as y0_ from bike this_ where this_.id=?
What the hell?
Forgot to add this was run under Grails 2.4.2 with Hibernate 4.