PrashantGupta
PrashantGupta

Reputation: 83

Filtering out objects according to their fields in a GORM query

I'm new at grails and stuck with a performance issue. I have three domain classes:

User{
Set authorities
static hasMany = [authorities: Role]
}

Organization{
//more code
}

UserOrganization{
User user
Organization organization
}

there are many roles (authorities) assigned to a user ('ROLE_ADMIN', 'ROLE_MANAGER')

In one scenario I have a list of organization and I need to find out all the users with manager authority (ROLE_MANAGER) of these organizations.

I tried using GORM like this:

UserOrganization.createCriteria().list{
inList('organizaton',organizationList)
//but do not know how to filter out users with ROLE_MANAGER authority
} 

Is there any way to get it done in single GORM query like this? I could get the list of all the Users of these organizations and run retainAll{closure} to filter out the managers but that would be a two step process and create a performance bottleneck.

Upvotes: 1

Views: 531

Answers (1)

Xeon
Xeon

Reputation: 5989

UserOrganization.createCriteria().list{
    inList('organizaton',organizationList)
    user {
        inList('authorities',authoritiesList)
    }
} 

Btw. you don't need explicitly write authorities GORM will create it for you:

User {
    static hasMany = [authorities: Role]
}

In case you want to ensure that authorities will be of Set or other collection type, you should then write: Set authorities

Upvotes: 1

Related Questions