2

假设我有这样的代码:

def c = Account.createCriteria()
def results = c {
    between("balance", 500, 1000)
    eq("branch", "London")
    or {
        like("holderFirstName", "Fred%")
        like("holderFirstName", "Barney%")
    }
    maxResults(10)
    order("holderLastName", "desc")
}

我想使用 lower() 函数将数据转换为小写

def c = Account.createCriteria()
def results = c {
    between("balance", 500, 1000)
    eq("branch", "London")
    or {


        like("lower(holderFirstName)", "Fred%")
        like("lower(holderFirstName)", "Barney%")


    }
    maxResults(10)
    order("holderLastName", "desc")
}

我的代码不起作用。什么是正确的语法?我对变音符号有疑问,所以我不想使用ilike

4

3 回答 3

3

Don't know which lower function you'd like to use but I guess you want to fetch data based on holderFirstName property ignoring the case.

Here you could use ilike, which is an case-insensitive like:

def c = Account.createCriteria()
def results = c.list {
    between("balance", 500, 1000)
    eq("branch", "London")
    or {
        ilike("holderFirstName", "Fred%")
        ilike("holderFirstName", "Barney%")
    }
    maxResults(10)
    order("holderLastName", "desc")
}

By the way - you missed to call list() on your criteria ...

Update

You could try to add a formula to your domain class like this:

static mapping = {
   lowerFirstName formula: "lower(holder_first_name)"

}

and change the property in your criteria to lowerFirstName:

like("lowerFirstName", "fred%") // changed 'Fred%' to 'fred%' 

Code is not tested but should work.

于 2013-05-14T13:05:15.677 回答
2

要在条件中使用数据库函数,您需要将sqlRestriction()添加的限制直接用于生成的 sql。

def c = Account.createCriteria()
def results = c.list {
...
  sqlRestriction("lower(holder_first_name) like '%%'")
}

请注意,您使用的是列名,而不是属性名。

于 2013-05-14T14:05:19.667 回答
1

如果您尝试比较不区分大小写,另一种选择是为此目的使用 ilike。Ilike 与 Like 类似,但不区分大小写。这里

如果您不想使用 ilike(添加到问题中),我认为您的替代方法是 executeQuery 和 hql。

Account.executeQuery(" select * from Account where .... or (lower(holderFirstName) = 'Fred%' ...")
于 2013-05-14T13:03:51.143 回答