Given the following example domains:
class UserRole implements Serializable {
User user
Role role
}
class User {
Set<Role> getRoles() {
UserRole.findAllByUser(this).collect { it.role } as Set
}
}
class Role {
Set<User> getUsers() {
UserRole.findAllByRole(this).collect { it.user } as Set
}
I can’t figure out how to build the criteria to find all the users with a given role. I tried the following:
def crit = User.createCriteria()
def results = crit.list {
roles {
eq('authority', 'ROLE_ADMIN')
}
}
However, it says it can’t find the property ‘roles’ in User. The reason I need a criteria for this is because there will be additional properties in User being searched on so dynamic finders won’t work for this situation.
If your expected result is small, it’s probably easy enough to just do this:
If you expect a large set of results, or you need to page over them, I’m not as certain. I’ll throw this out there, but I’ve never tried it. I don’t know if you can use
projections { property('association') }and have it work.I don’t think what you’re trying to do in your example will work, since you don’t actually have relationships defined on your
UserorRoleclasses that reference theUserRole(i.e. with ahasMany).