2011-11-19 87 views
3

我收到一个groovy.lang.MissingPropertyException每次我试图传递一个变量到一个where查询。2.0.0.RC1凡查询 - 没有这样的属性异常

这些都是我的领域类:

class Book { 
    String title 

    static belongsTo = [author: Author] 

    static constraints = { 
     title(blank: false, maxSize: 100) 
    } 
} 

class Author { 
    String name 

    static hasMany = [books: Book] 

    static constraints = { 
     name(unique: true, blank: false, maxSize: 50) 
    } 
} 

而这种测试方法引发异常:

@Test 
    void testWhereQuery() { 
     long authorId = 5 
     def query = Book.where { 
      author.id == authorId 
     } 

     def books = query.list() 
     assert books.size() == 0 
    } 

groovy.lang.MissingPropertyException: No such property: authorId for class: grails.gorm.DetachedCriteria 
    at grails.gorm.DetachedCriteria.methodMissing(DetachedCriteria.groovy:808) 
    at grails.gorm.DetachedCriteria.build(DetachedCriteria.groovy:723) 
    at org.grails.datastore.gorm.GormStaticApi.where(GormStaticApi.groovy:116) 
    at helloworld.BooksIntegrationTests.testWhereQuery(BooksIntegrationTests.groovy:38) 

我如何传递一个变量来查询?

回答

1

我自己问了这个问题,并发现查询似乎没有提供任何变量支持。只有命名的查询似乎能够做到这一点。

Parameters with new where queries in Grails 2.0

+0

我解决了某种方式将域对象作为变量传递。如果条件变成'author == _author',其中_author就像'def _author = Author.get(authorId)'一样工作。 –

+0

Author.get是一个动态注入方法,不使用where查询。您也可以使用.findBy ...,.findAll ...,.count等等。 – Todd

+0

对不起,我的意思是'def query = Book.where {author = Author.get(authorId)}'。你认为这会推迟执行直到调用list()吗? –

2

我也一直在争夺这一点。

试着改变你的地方查询:

def query = Book.where { 
    author.id.toString() == "${authorId}" 
} 

这个讨厌的方法只适用字符串内,是我一直能得到变量替换在工作,其中查询的唯一途径。

缺乏体面的支持参数化的地方查询使他们旁边没用,国际海事组织。耻辱,因为符号的格式非常简洁。

相关问题