gpt4 book ai didi

hibernate - Grails:使用Where查询选择具有给定id(子查询)的Child of Parent的子代

转载 作者:行者123 更新时间:2023-12-02 14:08:29 25 4
gpt4 key购买 nike

使用grails 2.1.0和默认的H2数据库。我有以下域:

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

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

我有一个任务ID,并希望使用全新的gorm where queries从该任务的(给定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项目是 available here

最佳答案

您应该提出这个问题。下面的示例编译并运行:

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

但是添加子查询会导致问题。至少,错误消息应该提供更多信息。但是我不明白为什么它在理论上是行不通的。

无论如何,与此同时,HQL可能是您最好的选择。

关于hibernate - Grails:使用Where查询选择具有给定id(子查询)的Child of Parent的子代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com