def c = Account.createCriteria()
def results = c.list {
like("holderFirstName", "Fred%")
and {
between("balance", 500, 1000)
eq("branch", "London")
}
maxResults(10)
order("holderLastName", "desc")
}
createCriteria
Purpose
Creates and returns an instance of Grails' HibernateCriteriaBuilder that can be used to construct criteria queries.
Unit tests use an in-memory implementation of GORM without Hibernate, and as such, createCriteria() returns an instance of CriteriaBuilder, not HibernateCriteriaBuilder.
|
Examples
The criterion methods (like, and, or, between etc) used to build the criteria can be statically imported from HibernateCriteriaBuilder (as in the following examples in this document), or written as "c.like(…)", "c.between(…)" etc.
To use pagination you would have to make another query to retrieve the total number of matching results. A better way is to pass the pagination values as arguments to the criteria method as shown below:
def c = Account.createCriteria()
def results = c.list (max: 10, offset: 10) {
like("holderFirstName", "Fred%")
and {
between("balance", 500, 1000)
eq("branch", "London")
}
order("holderLastName", "desc")
}
Because that query includes pagination parameters (max and offset), this will return a PagedResultList which has a getTotalCount() method to return the total number of matching records for pagination. Two queries are still run, but they are run for you and the results and total count are combined in the PagedResultList.
println "Rendering ${results.size()} Accounts of ${results.totalCount}"
The sort and order arguments accepted alongside the pagination values are checked the same way as for list(): sort must be a property path made up of identifiers separated by dots that resolves through the domain class mapping, and order must be "asc" or "desc" (case-insensitive, surrounding whitespace ignored). Any other value is rejected with an IllegalArgumentException before the query is built, so request parameters can be passed through without further checks. A dotted sort key whose first segment is an alias created with createAlias is left for the query to resolve; a bare name must be a property of the domain class.
Description
Criteria queries are a type-safe, advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better alternative to using a StringBuilder to dynamically construct an HQL query. Refer to the criteria sections in the GORM for Hibernate 7 or Hibernate 5 guide for usage instructions.
Association aliases
With Hibernate, createAlias('association', 'alias') creates an inner join and lets you refer to the association as alias.property.
In both Hibernate 5 and Hibernate 7, the three-argument overload accepts 0 for an inner join, 1 for a left outer join, or 2 for a right outer join. Hibernate 5 also supports 4 for a full join. Hibernate 7 does not support full joins through this overload: any value other than 1 or 2, including 4, produces an inner join.
For example, to include books with no author as well as books whose author has a name:
def books = Book.createCriteria().list {
createAlias('author', 'a', 1) // left outer join
or {
isNull('author')
isNotNull('a.name')
}
}
The alias uses the requested join type. A left join alone does not guarantee that unmatched rows remain in the result: the restrictions must also allow the missing association, as the or block does above.
In Hibernate 7, every explicitly requested alias of an entity association creates a join even when no restriction, projection, or order references it. Declaring a left alias and an inner alias for the same association therefore excludes rows with no associated entity, even if the inner alias is otherwise unused.
In Hibernate 7, an alias declared inside an association block is relative to that association, not the outer domain class. Hibernate 5 resolves the alias path from the domain class being queried. In Hibernate 7, every list, listDistinct, get, count and scroll call on a builder starts a new query, and nothing set in the closure of an earlier call carries over: not the criteria, projections, aliases, joins, paging, lock, readOnly or cache. What was set on the builder before a call, such as maxResults(1), applies to that call only. Hibernate 5 runs one query on a builder and refuses a second call.
In Hibernate 7, an entity alias declared inside an association block creates its requested join in that association’s scope even if the alias is unused. This applies to lists, counts, and paginated totals.
In a Hibernate 7 detached subquery, a plain association path uses the subquery’s own root when its entity has that association. Otherwise, it can reference an existing enclosing query join for correlation. An explicitly named outer alias can also be used to correlate the queries.
The enclosing join may also come from an association block in an outer detached query. For example, after favorite { isNotNull('label') }, an exists subquery over an entity without a favorite association can correlate using eqProperty('favorite.label', 'label'). Put the association block before the exists restriction.
For Hibernate 7-specific rules on alias/path precedence, collection aliases, counts, and subquery scoping, see Association Aliases in the GORM for Hibernate 7 guide.
Method reference
| Method | Description |
|---|---|
list |
The default method; returns all matching rows. |
get |
Returns a unique result, i.e. just one row. The criteria has to be formed that way, that it only queries one row. This method is not to be confused with a limit to just the first row. |
singleResult |
Alias for get. |
scroll |
Returns a scrollable result set |
listDistinct |
If subqueries or associations are used, one may end up with the same row multiple times in the result set. In Hibernate one would do a "CriteriaSpecification.DISTINCT_ROOT_ENTITY". In Grails one can do it by just using this method. |
The listDistinct() method does not work well with the pagination options maxResult and firstResult. If you need distinct results with pagination, we currently recommend that you use HQL.
|
If you invoke the builder with no method name
c { ... }
the list() method will be invoked automatically. In other words, it’s the equivalent of
c.list { ... }
Below is a node reference for each criterion method:
| Node | Description | Example |
|---|---|---|
between |
Where the property value is between two distinct values |
|
eq |
Where a property equals a particular value. |
|
eq (case-insensitive) |
A version of eq that supports an optional 3rd Map parameter to specify that the query be case-insensitive. |
|
eqProperty |
Where one property must equal another |
|
gt |
Where a property is greater than a particular value |
|
gtProperty |
Where one property must be greater than another |
|
ge |
Where a property is greater than or equal to a particular value |
|
geProperty |
Where one property must be greater than or equal to another |
|
idEq |
Where an objects id equals the specified value |
|
ilike |
A case-insensitive 'like' expression |
|
in |
Where a property is contained within the specified list of values. Can also be chained with the |
|
inList |
Same as |
|
isEmpty |
Where a collection property is empty |
|
isNotEmpty |
Where a collection property is not empty |
|
isNull |
Where a property is |
|
isNotNull |
Where a property is not |
|
lt |
Where a property is less than a particular value |
|
ltProperty |
Where one property must be less than another |
|
le |
Where a property is less than or equal to a particular value |
|
leProperty |
Where one property must be less than or equal to another |
|
like |
Equivalent to SQL like expression |
|
ne |
Where a property does not equal a particular value |
|
neProperty |
Where one property does not equal another |
|
order |
Order the results by a particular property |
|
rlike |
Similar to like, but uses a regex. Supported on MySQL, MariaDB, PostgreSQL, Oracle, H2 and Db2 for Linux, UNIX and Windows and for IBM i. On any other database, such as SQL Server and Db2 for z/OS, it falls back to like with Hibernate 5 and 7 alike, so the pattern is matched as a like pattern and not as a regex. Whether the match ignores case follows the database: it does on MySQL and MariaDB with a case-insensitive collation, it does not on Oracle, H2 and Db2, and on PostgreSQL it does with Hibernate 5 ( |
|
sizeEq |
Where a collection property’s size equals a particular value |
|
sizeGt |
Where a collection property’s size is greater than a particular value |
|
sizeGe |
Where a collection property’s size is greater than or equal to a particular value |
|
sizeLt |
Where a collection property’s size is less than a particular value |
|
sizeLe |
Where a collection property’s size is less than or equal to a particular value |
|
sizeNe |
Where a collection property’s size is not equal to a particular value |
|
sqlRestriction |
Use arbitrary SQL to modify the resultset |
|
With dynamic finders, you have access to options such as max, sort, etc. These are available to criteria queries as well, but they have different names:
| Name | Description | Example |
|---|---|---|
order(String, String) |
Specifies both the sort column (the first argument) and the sort order (either 'asc' or 'desc'). |
|
firstResult(int) |
Specifies the offset for the results. A value of 0 will return all records up to the maximum specified. |
|
maxResults(int) |
Specifies the maximum number of records to return. |
|
cache(boolean) |
Indicates if the query should be cached (if the query cache is enabled). |
|
readOnly(boolean) |
Indicates if the entities returned by the query should be read-only (no dirty checking). |
|
lock(boolean) |
Indicates if a pessimistic write lock should be obtained. |
|
fetchMode(String, FetchMode) |
Specifies the fetching strategy for an association. |
|
Criteria also support the notion of projections. A projection is used to change the nature of the results. For example the following query uses a projection to count the number of distinct branch names that exist for each Account:
def c = Account.createCriteria()
def branchCount = c.get {
projections {
countDistinct "branch"
}
}
The following table summarizes the different projections and what they do:
| Name | Description | Example |
|---|---|---|
property |
Returns the given property in the returned results |
|
distinct |
Returns results using a single or collection of distinct property names |
|
avg |
Returns the average value of the given property |
|
count |
Returns the count of the given property name |
|
countDistinct |
Returns the count of the given property name for distinct rows |
|
groupProperty |
Groups the results by the given property |
|
max |
Returns the maximum value of the given property |
|
min |
Returns the minimum value of the given property |
|
sum |
Returns the sum of the given property |
|
rowCount |
Returns count of the number of rows returned |
|