8

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?

Pma
  • 1,063
  • 1
  • 16
  • 30
  • What error do you get? Simply saying you get one is less than useful. – cdeszaq Sep 19 '12 at 17:29
  • It just does not work, gives error about incorrect hibernate query (that param #1 is not set), and i see a `where id=?` in the query therefore i think the `findAllByRoles` method did not have any effect. I think there must be another way of querying associations which contain simple types like `String` – Pma Sep 19 '12 at 19:57
  • Check the solution using GORM criteria here: http://stackoverflow.com/a/24211973/3738761 – Igor Aguiar Jun 13 '14 at 18:50

2 Answers2

5

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!

Roberto Perez Alcolea
  • 1,408
  • 11
  • 11
0

I have the same problem How to find records by value in their association property via DetachedCriteria

I made some investigation and, as I found, it's impossible. The GORM DSL itself doesn't have any method to check that value contains in association. It conains oly that criterias that are in SQL: AND, OR, IN.

But! You can join association as table in criteria Querying by Association Redux

Community
  • 1
  • 1
Sergey Ponomarev
  • 2,947
  • 1
  • 33
  • 43