Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails find() using 3 fields/columns (i.e. a find with multiple columns)

Tags:

grails

I'm a little confused about the Grails HQL documentation. Say I have a domain class with 3 fields,

class Example {
   String a 
   String b
   String c
 }

and I want to do the equivalent of an Example.findByAAndBAndC(), can you show me the line of code that I'd use to set that up and pass in the 3 parameters? Note the documentation says, one can at most use two fields for the findBy. I need to do 3 fields.

Thanks

like image 697
Ray Avatar asked Nov 15 '11 23:11

Ray


3 Answers

AFAIK you can't use dynamic finders if you have more than 2 predicates. Use a criteria query instead:

def results = Example.withCriteria {
  eq('a', 'some-a')
  eq('b', 'some-b')
  eq('c', 'some-c')
}

Update

By default, the predicates are combined using AND, if you want OR instead use:

def results = Example.withCriteria {
  or {
    eq('a', 'some-a')
    eq('b', 'some-b')
    eq('c', 'some-c')
  }
}
like image 166
Dónal Avatar answered Oct 19 '22 22:10

Dónal


i use in my project:

Example.findAllByAIlikeAndBIlikeAndCIlike("${a}%","${b}%","${c}%",[max:5, offset:0, sort:"a", order:"asc"])

and it works!

like image 28
jenk Avatar answered Oct 19 '22 23:10

jenk


Ray,

There are a few ways to "find" objects.

findWhere:

Example.findWhere(a:"Hello", B:"World")
Example.findByAandB("a value", "b value)

I'd suggest you to have a good read at:

http://grails.org/doc/latest/guide/ and
http://grails.org/doc/latest/guide/single.html#5.4.2%20Criteria

The documentation is quite good and has several examples.

like image 4
Guilherme Silva Avatar answered Oct 19 '22 21:10

Guilherme Silva