【问题标题】:How do I use 'in' in criteria to query sub-objects?如何在条件中使用“in”来查询子对象?
【发布时间】:2015-07-01 17:39:32
【问题描述】:

我想查询给定列表中具有子对象的所有对象。

class Parent {
    Child child

    static namedQueries = {
        getParentsByListOfChildren { childList ->
            'in'('child', childList.collect {it.id})
        }
    }
}

class Child {
}

def listOfChildren = [child1, child2]  // child1 and child2 are instances of Child
def results = Parent.getParentsByListOfChildren(listOfChildren)

我在集成测试中遇到以下异常:

property.BasicPropertyAccessor HHH000122: IllegalArgumentException in class: com.me.Parent, getter method of property: id
| Failure:  getParentsByListOfChildren correctly filters trains (com.me.ParentIntegrationSpec)
|  org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.me.parent.id
    at org.grails.datastore.gorm.GormStaticApi.withCriteria_closure11(GormStaticApi.groovy:304)
    at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:302)
    at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:37)
    at org.grails.datastore.gorm.GormStaticApi.withCriteria(GormStaticApi.groovy:303)

如何在对象不是简单对象的条件下使用in?我假设我需要使用 Child 的 id?

【问题讨论】:

  • 'in'('child.id', childList*.id )
  • 完美,非常感谢您这么快的回复!

标签: hibernate grails grails-orm criteria hibernate-criteria


【解决方案1】:

除了@dmahapatro 建议的一种之外,还有另外两种编写条件查询的方法。我将它们指向这里以供参考。

解决方案 1:@dmahapatro 建议

getParentsByListOfChildren { childList ->
    'in'('child.id', childList*.id )
}

解决方案 2

getParentsByListOfChildren { childList ->
    createAlias("child", "childFoo")   // Name is just an example, you can use anything in second parameter
    'in'('childFoo.id', childList*.id)
}

解决方案 3

getParentsByListOfChildren { childList ->
    child {
        'in'('id', childList*.id)
    }
}

都差不多,只是写法根据方便不同。

【讨论】:

  • 解决方案 3 与其他解决方案略有不同。 :) 在这种情况下,“孩子”也将与对父母的查询一起被急切地获取。
  • 在某些情况下,是的...如果在 DSL 中如上所述引用关联,那么如果关联的子节点数量巨大,则可能会影响性能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2015-10-08
  • 2018-11-21
相关资源
最近更新 更多