具有自定义联接表域的标准多对多
给出以下示例域:
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
}
我无法弄清楚如何构建标准来查找具有给定角色的所有用户。我尝试了以下操作:
def crit = User.createCriteria()
def results = crit.list {
roles {
eq('authority', 'ROLE_ADMIN')
}
}
但是,它说无法在 User 中找到属性“角色”。我需要一个标准的原因是因为正在搜索的用户中会有其他属性,因此动态查找器不适用于这种情况。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的预期结果很小,那么执行此操作可能很容易:
如果您预期有大量结果,或者您需要翻阅它们,我不太确定。我会把这个扔出去,但我从未尝试过。我不知道您是否可以使用
projections { property('association') }
并使其正常工作。我认为您在示例中尝试执行的操作不会起作用,因为您实际上没有在引用的
User
或Role
类上定义关系UserRole
(即具有hasMany
)。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
User
orRole
classes that reference theUserRole
(i.e. with ahasMany
).