Skip to content

Instantly share code, notes, and snippets.

@gregopet
Created July 29, 2014 15:50
Show Gist options
  • Save gregopet/4e6834b30c5cbcdf0ae1 to your computer and use it in GitHub Desktop.
Save gregopet/4e6834b30c5cbcdf0ae1 to your computer and use it in GitHub Desktop.
Grails where query oddities..

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?

@gregopet
Copy link
Author

Forgot to add this was run under Grails 2.4.2 with Hibernate 4.

@gregopet
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment