在 Grails 中对非字符串列使用 like

Using like to non-string columns in Grails

我目前正在开发一项 Grails 查询服务,该服务涉及使用名为 filterText.

的特定条件从数据库中检索 row/s
List getAdjustmentCodes(params) {
    def filterText = params.filterText
    .
    .
    .
    adjustmentCodeList = AdjustmentCode.findAll{
        or {
            ilike('description', "%$filterText%")
            // ilike('id', "%$filterText%")
        }                       
    }

    return adjustmentCodeList
}

请注意,我注释掉了 ilike('id', "%$filterText%") 行,因为当程序到达该行时,它会抛出一个错误:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.lang.Long for value...

可能 因为那个 table 的 id 列的类型是 long:

class AdjustmentCode implements Serializable {
    Long id
    String description
    String type
    String status
    Date statusDate
    String lastUpdateBy
    Date lastUpdateDate

    static mapping = {
        table 'RFADJUSTCDOTB'
        version false
        id column : 'ADJUS_CD'
        description column : 'ADJUS_DESC'
        type column : 'ADJUS_TYPE'
        status column : 'ADJUS_STATCD'
        statusDate column : 'ADJUS_STATDTE'
        lastUpdateBy column : 'ADJUS_LUPDBY'
        lastUpdateDate column : 'ADJUS_LUPDDTE'
    }

    .
    .
    .
}

但我需要为该列使用 like 运算符。例如,用户想要搜索 code 类似于 00002312123 的调整。这是使用 like 运算符的正确方法,还是有任何其他方法。谢谢你的回答。

我看过这个 post,但它没有说明如何在 or 子句中的 like 上使用非字符串。

ilike 仅适用于 Strings(文本)。您不能将它用于其他数据类型。使用不敏感(与字符串有关)没有意义。这不是 Grails 或 Hibernate 的限制,而是 SQL 函数的方式。

改用 like 运算符。

这个问题之前有人问过,has been answered(从hibernate的角度)

这里有一个替代方案:

class AdjustmentCode implements Serializable {
    Long id
    String description
    .....
    String idAsString
    static mapping = {
        table 'RFADJUSTCDOTB'
        ...
        idAsString formula('to_char(id)') // Or use an equivalent fn to convert it to a String
}

然后您可以按如下方式使用 ilike:

ilike('idAsString', "%${filterText}%")

我想这是一个懒惰的出路,但它应该有效。