Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: find by one-to-many association with String

I have a following domain class:

class User {
   static hasMany = [roles:String]
}

I would like to find every user which has role ROLE_ADMIN. Is there any possibility to do that with dynamic finders? user.findAllByRoles('ROLE_ADMIN') seems to give me an error.

UPDATE: it is quite easy to query association where Class A has a list of class B instances and both A and B are domain classes. But here class A is a domain class and class B is a simple Java string.

The code for querying association containing list of another domain objects would look like this:

`User.findAll { roles { role_name=='ROLE_ADMIN' } }`

What i am looking for is a way to specify the value of a String, for example:

`User.findAll { roles {THIS_VALUE=='ROLE_ADMIN' }}`

UPDATE 2: as far as i have found it is not possible to use criteria with collections of primitive types. It is possible to use HQL though:

User.findAll("from User a where :roles in elements(roles)",[roles:'ROLE_ADMIN'])

However it is not as usefull as a findAll or where query. I cannot chain findAll methods so defining other methods that for example: get ROLE_ADMIN users with username like 'xxx' requires rewriting whole HQL query. Maybe it is possible to express above HQL condition in form of a where expression?

like image 413
Pma Avatar asked Sep 19 '12 12:09

Pma


1 Answers

Maybe you can do something like:

if you have already a user list (userList)

def list = userList.findAll { user -> user.roles =~ 'ROLE_ADMIN' }

Hope this help!

like image 166
Roberto Perez Alcolea Avatar answered Nov 20 '22 11:11

Roberto Perez Alcolea