Grails Queries
http://techbus.safaribooksonline.com/book/programming/java/9781430243779/chapter-9-gorm/s152_152_html?uicode=netflix
http://techbus.safaribooksonline.com/book/programming/java/9781430248064/chapter-6-building-domains-and-services/navpoint-58?uicode=netflix
http://techbus.safaribooksonline.com/book/programming/9781449324513/5dot-hibernate/_sql_logging_html?uicode=netflix
//Config.groovylog4j = { debug "org.hibernate.SQL" trace "org.hibernate.type.descriptor.sql.BasicBinder"}
//DataSource.groovy datasource = { logSql = true}
hibernate { format_sql = true use_sql_comments = true}
Methods
Single Multiple
findBy findAllBy
findWhere findAllWhere
get getAll
count -
- list & listOrderBy
findByTodo t = Todo.findByPriorityAndStatus("2", "ACTIVE")
List<Todo> lt = Todo.findAllByName("App")List<Todo> lt = Todo.findAllByPriorityOrStatus("2", "ACTIVE")
List<Todo> lt = Todo.findAllByName("App", [max: 10, offset: 20, sort: "priority", order: "desc"])
findBy Examples// retrieve an album where the title contains 'Shake'def album = Album.findByTitleLike('%Shake%')
// get an album created in last 10 daysdef today = new Date()def last10Days = Album.findByDateCreatedBetween(today-10,today)
// first album that is not 'Rock'def somethingElse = Album.findByGenreNotEqual('Rock')
findWhereTodo t = Todo.findWhere([ "priority": "1", status: "ACTIVE"])
List<Todo> t = Todo.findAllWhere([ "priority": "1", status: "ACTIVE"])
getTodo t = Todo.get() //gets one record. if multiple exists then throws error.Todo t = Todo.get(1)
List<Todo> lt = Todo.getAll(1,3,5)List<Todo> lt = Todo.getAll([1,3,5])
listList<Todo> t = Todo.list()List<Todo> t = Todo.listOrderByName()
List<Todo> t = Todo.list([max: 10, offset: 20, sort: "priority", order: "desc"])List<Todo> t = Todo.list(max: 10, offset: 20, sort: "priority", order: "desc")
max - Specifies the maximum number of rows to return
offset - Specifies the number of elements into the ResultSet to start at when returning values (useful for pagination)
sort - Specifies the field to sort on in the returned list
order - Specifies the order of the sort: "asc" or "desc" (default is "asc")
ignoreCase - Sets sorting to ignore case (true by default)
fetch - Specifies eager/lazy fetch strategy as a Map of options
http://techbus.safaribooksonline.com/book/programming/java/9781617290961/chapter-5dot-retrieving-the-data-you-need/ch05lev1sec2_html?uicode=netflix
List<Contract> searchContracts(Map params) {return Contract.where {
if(params.contractId) {id == params.contractId
}if(params.contractName) {
contractName =~ '%'+params.contractName+'%'}if(params.supplierName) {
supplier.supplierName =~ '%'+params.supplierName+'%'
}}.list(max: 50, offset: page, sort: 'id', order: 'desc')
}
Operator Criteria Method Description
== eq Equal to
!= ne Not equal to
> gt Greater than
< lt Less than
>= ge Greater than or equal to
<= le Less than or equal to
in inList Contained within the given list
==~ like Like a given string
=~ ilike Case insensitive like
Detached CriteriaDetachedCriteria<Person> query = Person.where {
(lastName != "Simpson" && firstName != "Fred") ||
(firstName == "Bart" && age in 18..65)}
List<Person> results = query.list(sort:"firstName")
DetachedCriteria<Person> noMiddleName = Person.where { middleName == null}
Aggregate functions
Method Description
avg The average of all values
sum The sum of all values
max The maximum value
min The minimum value
count The count of all values
property Retrieves a property of the resulting entities
functions
Method Description
second The second of a date property
minute The minute of a date property
hour The hour of a date property
day The day of the month of a date property
month The month of a date property
year The year of a date property
lower Converts a string property to upper case
upper Converts a string property to lower case
length The length of a string property
trim Trims a string property
Collections & Subqueriesfinal query = Person.where { age > avg(age)}
def query = Person.where { age > avg(age).of { lastName == "Simpson" } && firstName == "Homer"}
Person.where { age < property(age).of { lastName == "Simpson" }}
Bulk Update/Deletedef query = Person.where { lastName == 'Simpson'}int total = query.updateAll(lastName:"Bloggs")
def query = Person.where { lastName == 'Simpson'}int total = query.deleteAll()
Dynamicvoid testFindingTodosWithCriteria() { def params = [ name: '%Second%', status: '4' ] def todos = executeCriteriaQuery( params ) assert todos[0].name == "Our Second Web App"}
List executeCriteriaQuery(def params) {def todos = Todo.createCriteria().list { and { params.each {key, value -> like(key, value) } } }
findTodo.find("From Todo as t
where t.name = :name and t.priority = :priority order by t.priority asc", [priority :"2", name : "Test"])
Todo.findAll("From Todo t where t.priority = :priority",[priority:"1"], [max: 10, offset: 20, sort: "priority", order "desc"])
executeQueryTodo.executeQuery("select t.name from Todo t where t.priority =
:priority ", [priority:"1"])
def users = User.executeQuery( 'from User u where u.username=:login or u.email=:login', [login: ‘hd’])
Aggregate funcdef newAuthors = Author.executeQuery( "select a from Author a where a.books is empty")
def prolificAuthors = Author.executeQuery( "select a from Author a where size(a.books) > 10")
def grailsAuthors = Author.executeQuery( "select a from Author a join a.books as book " + "where lower(book.title) like '%grails%'")
def author = Author.executeQuery( "select a from Author a where :book in elements(a.books)", [book: book])
Different return typesList<String> firstNames = Author.executeQuery('select a.firstName from Author a')
List<Object[]> names = Author.executeQuery('select a.name, a.age from Author a')
List<Map> names = Author.executeQuery( 'select new map(a.name as fullName, a.age as age) from Author a where ...')
Return a POGOList<Address> names = Author.executeQuery( 'select new Address(a.street, a.city, a.state, a.zip) from Author a where ...')
class Author {Author(String street, String city, String state, String zip) {
...}
Author() {..}}
filter map optionsmax - Limits the maximum number of records to return (typically for pagination)offset - Specifies the offset position into the results (typically for pagination)readOnly - If true, will return results that are not dirty-checked fetchSize - Specifies the fetch size for the underlying JDBC querytimeout - Specifies the timeout for the underlying JDBC queryflushMode - Overrides the current session flush modecache - If true, will use the query cache
http://techbus.safaribooksonline.com/book/programming/java/9781430243779/chapter-9-gorm/s174_174_html?uicode=netflix