开发者

Criteria Many-to-Many With Custom Join Table Domain

Given the following example domains:

class UserRole implements Seriali开发者_Python百科zable {
  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:

def c = UserRole.createCriteria()
def users = c.list {
    role {
        eq('authority', 'ROLE_ADMIN')
    }
    user {
        // additional user property constraints
    }
}.collect { it.user }

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.

def c = UserRole.createCriteria()
def users = c.list {
    projections {
        property('user') // never tried this, but worth a shot
    }
    role {
        eq('authority', 'ROLE_ADMIN')
    }
    user {
        // additional user property constraints
    }
}

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 User or Role classes that reference the UserRole (i.e. with a hasMany).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜