Question

I have Parent classes and two Child1 and Child2 inherited from it:

class Parent { }
class Child1 extends Parent {
    String prop1
}
class Child2 extends Parent {
    String prop2
}

And now I need to write select all Parent clases, but with criteria on prop1 and prop2, i.e. something like this

DetachedCriteria crit = Parent.where {
    (prop1 == 'Some value') || (prop2 == 'Some value')
}
crit.list()

How can I do that?

Was it helpful?

Solution

The short answer is, you can't query a class based on the properties of sub classes unless they are inherited. The parent has no concept of the properties of the sub classes in your example since they aren't inherited, making your query impossible. The best solution is going to be to query each of the sub classes individually and then merge the results.

OTHER TIPS

Using sqlRestriction you can add arbitrary conditions to your query, so this might work

DetachedCriteria crit = Parent.where{
    sqlRestriction 'prop1 = ? OR prop2 = ?', ['value1', 'value2]
}

The only drawback is that SqlRestriction is not supported in unit tests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top