简体   繁体   English

Grails GORM(休眠)查询

[英]Grails GORM (Hibernate) query

I'm trying to do the below sql statement in GORM 我正在尝试在GORM中执行以下sql语句

select * from table1 where table1.x not in
      (select x from table 2 where y='something');

so, I have two tables, and needs to find the entries from table 1 which are not in table 2. In Grails 因此,我有两个表,需要从表1中找到不在表2中的条目。

def xx= table2.findByY('something')
    def c = table1.createCriteria()
    def result= c.list {
      not (
        in('x', xx)
    )
}

the syntax is wrong, and I'm not sure how to simulate not in sql logic. 语法错误,而且我不确定如何 sql逻辑中模拟。

As a learning point, if someone can also tell me why minus (-) operator in grails/groovy doesn't work with list. 作为学习点,如果有人也可以告诉我,为什么grails / groovy中的减号(-)运算符不适用于list。 I tried getting x and y seperately, and doing x.minus(y), but it doesn't change the list. 我尝试分别获取x和y,并执行x.minus(y),但它不会更改列表。 I saw an explanation at Groovy on Grails list - not working? 我在Groovy上的Grails列表上看到了一个解释-不起作用吗? , but I would expect the list defined are local. ,但我希望定义的列表是本地的。

thank you so much. 非常感谢。

嗯,我只是在自己学习GORM,但我看到的一件事是in是groovy中的保留字,因此需要转为in

Ok.. got to work.. anyone interested.. 好..开始工作..任何有兴趣的人..

Stephen was right, you have to escape in with 'in', as it is a reserved word. 斯蒂芬说得对,您必须以“中”来逃脱,因为这是保留字。 the syntax is. 语法是。

def c = table1.createCriteria()
    def result= c.list {
      not {
        'in'("x", xx)
//xx could be a list, array etc. eg: [1,2,3]
    }
}

Since Grails 2.4 , you can write this query as a single query using a subquery via notIn & DetachedCriteria(where) : 从Grails 2.4开始,您可以通过notInDetachedCriteria(where)使用子查询将此查询编写为单个查询:

& we have two syntax : &我们有两种语法

@java.lang.Override public Criteria notIn(java.lang.String propertyName, QueryableCriteria<?> subquery)

@java.lang.Override public Criteria notIn(java.lang.String propertyName, groovy.lang.Closure<?> subquery)

For your case , following should works: 对于您的情况,以下方法应该有效:

def c = Tabl1.createCriteria().list {
              notIn 'x',Table2.where { eq('y','something') }.projections {
                     property 'x'
                     }.list()
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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