简体   繁体   中英

Grails Criteria query with a condition on data

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.

This will do?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM