Reputation: 13811
I have User
class which has a field type
, which is in turn a list.
So type
might look like : ["a","b"]
I have a another list, say search
like ["c","b"]
(this is pre-defined)
Now what I want is to search all my User
instances such that I can find users type
matching with any one of the elements from search
.
I came up with a partial solution :
def newQ = User.findAllByUsernameIsNotNull()
newQ.each { eachIndex ->
query = eachIndex.type
result = query.findAll { it == "c" }
if(result.size() > 0 )
{
ans << eachIndex.username
}
}
The above code works, ans
list have all User
which satisfy my condition. But you can clearly see that in query.findAll
line, I'm doing a search only for one element from search
. I want to perform search operation for all search
element against query
(which is User
's type
field).
How can I achieve that? Apart from my solution are there any easy way to do that?
Thanks in advance.
Upvotes: 1
Views: 707
Reputation: 3243
When searching you want to go to the database as few times as possible since those are usually the most expensive operations. If the User.withCriteria {..} works I'd use that (I'm not as familiar with .withCriteria{}). This would work as well if you still wanted to use the dynamic finders since mockDomain doesn't work with HSQL (again not sure if .withCriteria{} works with mockDomain).
def search = ["c", "b"]
def users = User.findAllByUsernameIsNotNull()
users = users.findAll {it.type.intersect(search)}
Upvotes: 0
Reputation: 4882
You could do something like:
def ans = []
search.each{s->
ans += User.findAll("from User u where u.username is not null and ? in elements(u.type)",[s])
}
I can't think of a way to do it in a single query
Upvotes: 2