【问题标题】:Grails Criteria query with a condition on data带有数据条件的 Grails Criteria 查询
【发布时间】:2015-01-16 04:05:15
【问题描述】:

我有一个使用 vanilla GORM 存储此 Grails 域类的数据的数据库表:

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

我想创建一个搜索查询,如果 propOver 属性包含值,则搜索它,否则搜索 propBase 属性。或者,换种说法,propOver 会在 propBase 存在时覆盖它。

我需要类似这个伪代码的东西:

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

有可能吗?

请注意,一个(不好的)解决方案是创建一个存储propOver ?: propBase 值的第三个属性,但它违反了 DRY 原则,我宁愿避免修改数据库。

【问题讨论】:

    标签: grails hibernate-criteria


    【解决方案1】:

    这样可以吗?

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

    【讨论】:

    • 是的,我想它会的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2011-11-03
    相关资源
    最近更新 更多