2011-11-19 84 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}" 
} 

這個討厭的方法只適用字符串內,是我一直能得到變量替換在工作,其中查詢的唯一途徑。

缺乏體面的支持參數化的地方查詢使他們旁邊沒用,國際海事組織。恥辱,因爲符號的格式非常簡潔。

相關問題