简体   繁体   中英

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?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM