5

What's the best way to write a Grails dynamic finder that is searching for a flag that equals 0 or is null?

Example

class Book {
    String title
    Date releaseDate
    String author
    Boolean paperback
    Integer isArchived
}

isArchived is nullable. So the query is either looking for isArchived = 0 or if it is null it also wants it in the results.

EDIT: At first glance this question just seems like I am not even trying and didn't glance at the documentation. I assure you that I have been researching and trying many different things.

Also, yes, a Boolean flag in a database should not be nullable, but it is not possible to change the table at this point in time. The developer in this case relied on setting the value of the flag to 0 by default in the domain object. While this worked in the majority of cases, there are certain scenarios where the flag gets set to null.

I have tried many different ways of doing this using dynamic finders but it seems like having the same column twice in a dynamic finder is not possible.

I would accept the answer, "No this is not possible using dynamic finders just use the createCriteria() method." I just want to know for sure if this is not possible.

anataliocs
  • 10,427
  • 6
  • 56
  • 72
  • Don't see any reason why to downvote this question, it's clear and can be useful. – lukelazarovic Dec 12 '13 at 20:03
  • 1
    @anataliocs - chill out a bit. If you had put the information in your question that is there after the edit to begin with, you would have received better feed back. Better questions get better answers and that usually boils down to more details. – Gregg Dec 12 '13 at 20:18
  • I apologize, it's just the problem seems so simple at first but is frustrating. I tried to add additional details to better frame my question. – anataliocs Dec 12 '13 at 20:20

1 Answers1

3

You could use the where feature, if the version of Grails you're using supports it:

def results = Book.where {
    (isArchived == null || isArchived == 0)
}

You could also use HQL:

Book.findAll("from book b where b.isArchived IS NULL or b.isArchived = 0")
Gregg
  • 34,973
  • 19
  • 109
  • 214
  • 1
    Could you use Groovy truth and write `Book.where { !isArchived }`? – doelleri Dec 12 '13 at 20:40
  • 1
    To better phrase my question, what is the best practice? Since it seems like a simple query I wanted to use a dynamic finder but I'm open to anything. – anataliocs Dec 13 '13 at 02:14