GORM createCriteria()“AND”问题

时间:2012-07-11 20:37:44

标签: grails gorm

2个域类,人员和属性

class Person {
static hasMany = [attributes : Attribute]    


}


class Attribute{
String key
String value
}

查询fname:

def c = Person.createCriteria()
def result = c.list{

attributes {
          eq("key", "fname")
          eq("value", "foo")
}   


println result
}

结果: [foo foo ,foo bar]

查询lname:

def c = Person.createCriteria()
def result = c.list{

attributes {
          eq("key", "lname")
          eq("value", "bar")
}   


println result
}

结果: [酒吧吧 ,foo bar]

查询lname或fname:

def c = Person.createCriteria()
def result = c.list{
or{
attributes {
          eq("key", "fname")
          eq("value", "foo")
}

attributes {
          eq("key", "lname")
          eq("value", "bar")
}
}

println result
}

结果: [foo foo ,foo吧 ,酒吧]

但如果我将OR更改为And,则无法获得结果:

def c = Person.createCriteria()
def result = c.list{
and{
attributes {
          eq("key", "fname")
          eq("value", "foo")
}

attributes {
          eq("key", "lname")
          eq("value", "bar")
}
}

println result
}

结果: []

1 个答案:

答案 0 :(得分:0)

我找到了一个肮脏的解决办法:

 def list1= Person.createCriteria().list { 
            attributes { 
                    eq("key", "fname") 
                    eq("value", "foo") 
            } 
        } 
def list2= Person.createCriteria().list { 
            attributes { 
                    eq("key", "lname") 
                    eq("value", "bar") 
            } 
        } 
        return list1.intersect(list2) 

Source

我会留下这个问题没有答案,希望有人会提出更好的建议