I use find for :
find("from domain d where d.id=? AND d.name=?",[params.id, params.name])
that gives me first matching result. Now I see there is findWhere() for :
Book.findWhere(author: params.author, title: params.title)
Also returns first matching result set. What is the basic difference and when to use either.
Thank you in advance.
Right, so I created a test app, created a test Domain class:
package test
class Book {
String title
String author
static constraints = {
}
}
Added some dummy data in the Bootstrap:
import test.*
class BootStrap {
def init = { servletContext ->
new Book( title:'Book 1', author:'Tim' ).save()
new Book( title:'Book 2', author:'Alice' ).save()
new Book( title:'Book 3', author:'Bob' ).save()
}
def destroy = {
}
}
And a test controller:
package test
import grails.converters.JSON
class BookController {
def test1() {
Book b = Book.find( "from Book as b where b.author = ? and b.title = ?", [ 'Tim', 'Book 1' ] )
render b as JSON
}
def test2() {
Book b = Book.findWhere( author:'Tim', title:'Book 1' )
render b as JSON
}
def test3() {
Book b = Book.findByAuthorAndTitle( 'Tim', 'Book 1' )
render b as JSON
}
}
Then, turned on hibernate logging by adding
trace 'org.hibernate.type'
debug 'org.hibernate.SQL'
to the log4j section of Config, and:
logSql = true
To the dataSource
section of DataSource.groovy.
Then, ran all 3 controller methods.
find
executes:
select book0_.id as id0_,
book0_.version as version0_,
book0_.author as author0_,
book0_.title as title0_
from book book0_
where book0_.author=? and book0_.title=? limit ?
findWhere
executes:
select this_.id as id0_0_,
this_.version as version0_0_,
this_.author as author0_0_,
this_.title as title0_0_
from book this_
where (this_.author=? and this_.title=?) limit ?
And findByAuthorAndTitle
gives us:
select this_.id as id0_0_,
this_.version as version0_0_,
this_.author as author0_0_,
this_.title as title0_0_
from book this_
where this_.author=? and this_.title=? limit ?
So as you can see, in this simplistic example they are just 3 ways of saying the same thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With