使用 findAllBy 时返回唯一结果
我在服务中有以下方法,请注意 def usersByRole
行上的 .user
:
def getUsersByRole(String desiredRole1, String desiredRole2, String desiredRole3) {
Role role1 = Role.findByAuthority(desiredRole1)
Role role2 = Role.findByAuthority(desiredRole2)
Role role3 = Role.findByAuthority(desiredRole3)
def usersByRole = UserRole.findAllByRoleInList([role1, role2, role3]).user
return usersByRole
}
它工作得很好,但是当用户具有多个角色时(即 ROLE_ADMIN
和 ROLE_OWNER
),如果前面提到的两个角色都作为参数给出,则该用户在集合中存在两次。有什么干净的方法可以使集合仅包含唯一的结果吗?
I have the following method in a service, please note the .user
on the def usersByRole
line:
def getUsersByRole(String desiredRole1, String desiredRole2, String desiredRole3) {
Role role1 = Role.findByAuthority(desiredRole1)
Role role2 = Role.findByAuthority(desiredRole2)
Role role3 = Role.findByAuthority(desiredRole3)
def usersByRole = UserRole.findAllByRoleInList([role1, role2, role3]).user
return usersByRole
}
It works good, but when a user has multiple roles (i.e. ROLE_ADMIN
, and ROLE_OWNER
) then that user exists twice in the collection if both of the previously mentioned roles are given as parameters. Is there any clean way I can make the collection contain only unique results?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以在这里找到与您类似的问题: GORM createCriteria 和 list 不返回相同的结果:我该怎么办?
方法 1
如果您想直接从数据库查询返回唯一的用户列表,那么您可以使用
User
上的listDistinct
(假设用户与UserRoles
具有roles
OneToMany 关联)方法 2
您还可以尝试直接查询
UserRole
并使用groupProperty
按用户分组(请参阅http://www.grails.org/doc/latest/ref/ Domain%20Classes/createCriteria.html)方法3
从返回的列表中删除重复的用户:
A similar question as yours can be found here: GORM createCriteria and list do not return the same results : what can I do?
Method 1
If you want to return unique list of users directly from DB query then you can use
listDistinct
onUser
(supposing that user has aroles
OneToMany association withUserRoles
)Method 2
You can also try to query
UserRole
directly and group by User using thegroupProperty
(see http://www.grails.org/doc/latest/ref/Domain%20Classes/createCriteria.html)Method 3
Remove duplicated users from the returned list:
查找器将返回一个
List
,调用.user
也会返回一个List
,但您可以作弊并将其转换为Set
它将删除重复项。由于不需要顺序(您正在返回 def,因此您似乎并不关心集合类型),因此您不需要将其转换回来:这假设您有一个很好的-在您的
User
类中定义了equals
和hashCode
,以便唯一性检查有意义。The finder will return a
List
, and calling.user
also returns aList
, but you can cheat and cast it to aSet
and it will remove duplicates. Since there's no order needed (you're returningdef
so it doesn't appear that you care about the collection type) you don't need to convert it back:This presumes that you have a well-defined
equals
andhashCode
in yourUser
class so the uniqueness check makes sense.