Top Banner
Grails Queries
38

Grails queries

Aug 14, 2015

Download

Software

Husain Dalal
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Grails   queries

Grails Queries

Page 2: 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

Page 3: Grails   queries

Configuration

Page 4: Grails   queries

http://techbus.safaribooksonline.com/book/programming/9781449324513/5dot-hibernate/_sql_logging_html?uicode=netflix

Page 5: Grails   queries

//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}

Page 6: Grails   queries

Dynamic Finders

Page 7: Grails   queries

Methods

Single Multiple

findBy findAllBy

findWhere findAllWhere

get getAll

count -

- list & listOrderBy

Page 8: Grails   queries

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"])

Page 9: Grails   queries

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')

Page 10: Grails   queries
Page 11: Grails   queries

findWhereTodo t = Todo.findWhere([ "priority": "1", status: "ACTIVE"])

List<Todo> t = Todo.findAllWhere([ "priority": "1", status: "ACTIVE"])

Page 12: Grails   queries

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])

Page 13: Grails   queries

countTodo.count()Todo.countByPriority('1')

Page 14: Grails   queries

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")

Page 15: Grails   queries

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

Page 16: Grails   queries

Where queries

Page 17: Grails   queries

http://techbus.safaribooksonline.com/book/programming/java/9781617290961/chapter-5dot-retrieving-the-data-you-need/ch05lev1sec2_html?uicode=netflix

Page 18: Grails   queries

User.where { loginId =~ myLoginId }.list()

Page 19: Grails   queries

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')

}

Page 20: Grails   queries

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

Page 21: Grails   queries

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}

Page 22: Grails   queries

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

Page 23: Grails   queries

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

Page 24: Grails   queries

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" }}

Page 25: Grails   queries

Bulk Update/Deletedef query = Person.where { lastName == 'Simpson'}int total = query.updateAll(lastName:"Bloggs")

def query = Person.where { lastName == 'Simpson'}int total = query.deleteAll()

Page 26: Grails   queries

Criteria Queries

Page 27: Grails   queries

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) } } }

Page 28: Grails   queries

HQL Queries

Page 29: Grails   queries

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"])

Page 30: Grails   queries

find by exampleTodo todo = new Todo()todo.name = "Test"todo = Todo.find(todo)

Page 31: Grails   queries

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’])

Page 32: Grails   queries

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])

Page 33: Grails   queries

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 ...')

Page 34: Grails   queries

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() {..}}

Page 35: Grails   queries

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

Page 36: Grails   queries

Performance

Page 37: Grails   queries

http://techbus.safaribooksonline.com/book/programming/java/9781430243779/chapter-9-gorm/s174_174_html?uicode=netflix

Page 38: Grails   queries

Caching