Grails Criteria query with a condition on data

1.1k Views Asked by At

I have a database table storing data for this Grails domain class using vanilla GORM:

class A {
    String propOver // may be null
    String propBase
}

I want to create a search query that searches against the propOver property if it contains a value, otherwise against the propBase property. Or, to word this differently, propOver overrides propBase when it exists.

I need something that works like this pseudo-code:

def results = A.createCriteria().list{
    if propOver isn't null: // the heart of the problem
         eq('propOver', search_input)
    else
         eq('propBase', search_input)
}

Is it even possible?

Please note that one (bad) solution would be to create a 3rd property that stores the propOver ?: propBase value, but it violates the DRY principle, and I'd prefer avoiding modifying the DB.

1

There are 1 best solutions below

1
On BEST ANSWER

This will do?

A.createCriteria().list{
    or {
        eq 'propOver', search_input
        and {
            isNull 'propOver'
            eq 'propBase', search_input
        }
    }
}