簡體   English   中英

Grails:使用Where查詢選擇具有給定ID(子查詢)的Child of Parent的子代

[英]Grails: selecting Children of Parent of Child with given id (subquery) with a Where Query

使用grails 2.1.0和默認的H2數據庫。 我有以下域:

class Project {
    static hasMany = [tasks: Task]
}

class Task {
    Date dateCreated
    static belongsTo = [project: Project]
}

我有一個任務ID,並希望使用全新的where where查詢從任務(給定ID)的項目中獲取所有任務。 這是我的嘗試:

def tasks = Task.where {
    project == property('project').of { id == firstTask.id }
}.list()

(firstTask.id是給定的任務ID,從測試中刪除了代碼)

令人不愉快的意外結果是:

IllegalArgumentException occurred calling getter of so.q.grom.subqueries.Project.id
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of so.q.grom.subqueries.Project.id
    at grails.gorm.DetachedCriteria.list_closure2(DetachedCriteria.groovy:639)
    at grails.gorm.DetachedCriteria.withPopulatedQuery_closure9(DetachedCriteria.groovy:890)
    at org.grails.datastore.gorm.GormStaticApi.withDatastoreSession_closure18(GormStaticApi.groovy:555)
    at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:301)
    at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:34)
    at org.grails.datastore.gorm.GormStaticApi.withDatastoreSession(GormStaticApi.groovy:554)
    at grails.gorm.DetachedCriteria.withPopulatedQuery(DetachedCriteria.groovy:873)
    at grails.gorm.DetachedCriteria.list(DetachedCriteria.groovy:638)
    at grails.gorm.DetachedCriteria.list(DetachedCriteria.groovy:637)
    at GormSubqueriesSpec.should get tasks from the same project(GormSubqueriesSpec.groovy:32)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
    ... 10 more

為什么!? :(有什么區別於:

def tasks = Task.findAll() {
    dateCreated < property('dateCreated').of { id == secondTask.id }
}

為了澄清,使用HQL,我想要的是:

def tasks = Task.findAll(
        'from Task task where task.project = (select t.project from Task t where t.id = :taskId)',
        [taskId: firstTask.id]
)

但我希望在“ where查詢”中使用它。

為了您的方便(我很精確), 此處提供了包含域和查詢測試的Grails項目

您應該提出這個問題。 以下示例編譯並運行:

def tasks = Task.where {
    project == property('project')
}.list()

但是添加子查詢會導致問題。 至少,錯誤消息應該提供更多信息。 但是我不明白為什么它在理論上是行不通的。

無論如何,與此同時,HQL可能是您最好的選擇。

通過動態查找器可能有一種更簡單的方法:

Task.findAllByProject( thisTask.project )

我不知道有關您的項目的詳細信息,但是您可以將此方法添加到域類Task中:

public Collection<Task> findAllTasksinPoject() {
    return Task.findAllByProject( project )
}

您可以在Task類的每個實例上調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM