They built a nice new feature in Grails 1.2 called “named queries“. Named queries can be defined in a domain class as static properties and support the criteria builder syntax.

Examples

package testapp

class User {
	String name
	int iq
	int age

	static namedQueries = {
		dumbUsers {
			int referenceIq = 60
			lt 'iq' , referenceIq
		}

		nameStartsWith { letter ->
			like 'name', '${letter}%'
		}

		midAges {
			between('age', 20, 40)
		}

	}
}

// count dumb users
println User.dumbUsers.count()

// print amount of users, usernames starting with an 'a'
User.nameStartsWith('a').count()

Article Updates

  • 2015-03-03: Table of contents added.