当前位置:  开发笔记 > 前端 > 正文

grails中find()和findWhere之间的区别

如何解决《grails中find()和findWhere之间的区别》经验,为你挑选了1个好方法。

我用find代替:

 find("from domain d where d.id=? AND d.name=?",[params.id, params.name])

这给了我第一个匹配的结果.现在我看到有findWhere()用于:

  Book.findWhere(author: params.author, title: params.title)

还返回第一个匹配的结果集.什么是基本区别以及何时使用.

先感谢您.



1> tim_yates..:

是的,所以我创建了一个测试应用程序,创建了一个测试Domain类:

package test

class Book {
    String title
    String author

    static constraints = {
    }
}

在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 = {
    }
}

还有一个测试控制器:

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

然后,通过添加打开hibernate日志记录

trace 'org.hibernate.type'
debug 'org.hibernate.SQL'

到Config的log4j部分,并且:

logSql = true

dataSourceDataSource.groovy 的部分.

然后,运行所有3种控制器方法.

find 执行:

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 执行:

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 ?

findByAuthorAndTitle告诉我们:

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 ?

正如您所看到的,在这个简单的例子中,他们只是说出同样事情的3种方式

推荐阅读
乐韵答题
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有