Search code examples
hibernategrailscriterianamed-query

Grails named query for NOT IN


Trying to come up with a succinct way to create a named query with NOT IN clause. Restrictions class does not seem to have a "not in" construct. Anyone know a good way to do this?

Solution:

static namedQueries = {
        activeOnly {
            eq 'active', true
        }
        open {
            ne 'state', this.STATE_COMPLETED
        }
        my { user ->
            or {
                eq 'createdBy', user
                eq 'reviewer', user
                eq 'assignee', user
                eq 'requestedFor', user
                ilike 'notifyList', "%$user%"
            }
        }
        topLevel {
            not {'in'('type', [RequestType.Part])}
        }
    }

Note: the word 'in'must be quoted because its reserved.

These named queries can be used like this:

Request.activeOnly.open.topLevel.list(params)

Solution

  • Maybe sombething like this:

    Book.findAll("from Book b where b.author not in (?)", ['Borges', 'Sabato', 'Cortazar'])
    

    or using a criteria

    Book.withCriteria {
        not {
            'in'('author', ['Borges', 'Sabato', 'Cortazar'])
        }
    }
    

    http://grails.org/doc/1.3.x/ref/Domain%20Classes/createCriteria.html - the docs for 'in' criterion method has a chained 'not' method also.