Advanced Criteria Queries Wednesday Session - 29th, June 2016 Presented by - Nakul
Criteria VS Detached CriteriaCriteria is created based on hibernate session. For example :-
template.getSessionFactory().getCurrentSession().createCriteria(Person.class);
DetachedCriteria is not dependent on hibernate session. For example :-
DetachedCriteria.forClass(Person.class);
Criteria VS Detached Criteria
Criteria Queries require a session to be present when the query is build up and
fired upon database.
Detached Criteria are criteria queries that are not associated with any given
database session/connection.
Detached Criteria queries have many uses including allowing you to create
common reusable criteria queries, execute subqueries and execute batch
updates/deletes.
Building Detached Criteria
import grails.gorm.*
…
def criteria = new DetachedCriteria(Person)
To build a normal criteria query you can use the build closure
def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'Simpson'
}
Executing Detached Criteria
Unlike regular criteria, Detached Criteria are lazy, in that no query is executed at
the point of definition.
list - List all matching entities
get - Return a single matching result
count - Count all matching records
deleteAll - Delete all matching records
updateAll(Map) - Update all matching records with the given properties
Executing Detached Criteriadef criteria = new DetachedCriteria(Person).build {
ilike 'lastName', 'LastName 2%'
projections{
'lastName'
}
}
def results = criteria.list(max: 8, sort: "lastName")
def results1 = criteria.list(max:8, sort:"lastName") {
gt 'age', 24
}
To retrieve a single result you can use the get or find methods (which are synonyms):
Person p = criteria.find() // or criteria.get()
Executing Detached CriteriaThe DetachedCriteria class itself also implements the Iterable interface
which means that it can be treated like a list:
def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'LastName 2%'
}
criteria.each {
println it.firstName
}
In this case the query is only executed when the each method is called. The same
applies to all other Groovy collection iteration methods.
Executing Detached CriteriaYou can also execute dynamic finders on DetachedCriteria just like on
domain classes. For example:
def criteria1 = new DetachedCriteria(Person).build {
ilike 'lastName', 'LastName 2%'
}
def person = criteria1.findByAge(76)
Batch Operations with Detached CriteriaThe DetachedCriteria class can be used to execute batch operations such as
batch updates and deletes. For example, the following query will update all people
with the surname "Simpson" to have the surname "Bloggs" -
def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'Simpson'
}
int total = criteria.updateAll(lastName:"Bloggs")
Batch Operations with Detached CriteriaThe DetachedCriteria class can be used to execute batch operations such as
batch updates and deletes. For example, the following query will update all people
with the surname "Simpson" to have the surname "Bloggs" -
def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'Simpson'
}
int total = criteria.updateAll(lastName:"Bloggs")
Batch Operations with Detached CriteriaTo batch delete records you can use the deleteAll method
def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'Nexthoughts'
}
int total = criteria.deleteAll()
Named QueriesThe namedQueries static property defines named queries.
Named queries support the criteria builder syntax.
static namedQueries = {
lastNameFilter {
ilike('lastName', 'Next%')
}
}
Executing Named Queries
// Lists All records from person where lastName ilike “Next%” -
List<Person> personList= Person.lastNameFilter.list()
//Get’s the first element
Person.lastNameFilter.get()
//Get total count of records present
Person.lastNameFilter.count()
Executing Named Queries
//Execute list as we did with criteria
Person.lastNameFilter.list(max: 5)
//Apply more criteria within the namedQuerry
Person.lastNameFilter{ lt ('age',65 as Long)}
References
1. The Definitive Guide to Grails 2 - Graeme Rocher & Jeff Scott Brown
2. Programming Grails - Burt Beckwith
3. Grails Documentation - Detached Criteria
4. http://tatiyants.com/how-and-when-to-use-various-gorm-querying-options/