可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Is there a way that, i can get list of distinct User
objects(based on username). And still get result as a List of User
Objects rather than, List of username's.
My code is
def criteria = User.createCriteria() def users = criteria.list() { projections { distinct("username") } setResultTransformer(CriteriaSpecification.ROOT_ENTITY) } return users
Currently am getting List of the usernames, not User.
回答1:
Ya projection is like filtering and selecting by username you should change it to
def criteria = User.createCriteria() def users = criteria.listDistinct() { projections { groupbyproperty("username") } // setResultTransformer(CriteriaSpecification.ROOT_ENTITY) } return users
JOB DONE!
回答2:
One of these should work - I haven't tested any of them, I leave that up to you :)
User.list().unique()
User.list().unique()
with the equals()
method on the User
domain class overridden to compare objects using the username
User.list().unique { it.username }
(might need toArray()
after list()
)
回答3:
Where ever you got a collection (list, array, ...) (I don't know if work with any type of collection, but work in all that i could test). Use unique{ it.property }
:
Example:
def users = [] for (def room in rooms) { users.addAll(room.users) } return users.unique{ it.id }
回答4:
This will get you the distinct user object based on userName
def userInstance = User.list().unique{ it.user_name}
回答5:
Using where query(Detached criteria):
def userListQuery = User.where{ // Your search criteria } def userList = userListQuery.list().unique{ it.username }
it should result one query for distinct results.
回答6:
def criteria = User.createCriteria() def users = criteria.list() { projections { distinct("username") } setResultTransformer(CriteriaSpecification.ROOT_ENTITY) }
Just replace setResultTransformer(CriteriaSpecification.ROOT_ENTITY) with resultTransformer(ALIAS_TO_ENTITY_MAP). You will get a list of string as a result
otherwise just replace .list with .listDistinct and use do not need distinct("username"), just can be property("username");
Usually people get problems with pagination. not results. If you already had something like:
User.createCriteria().list([max:params.max,offset:params.offset],{ createAlias("others", "others", CriteriaSpecification.LEFT_JOIN); ilike("others.firstName", "%${query}%"); });
It could result in row duplicates. Because .listDistinct() does not support pagination, just add
resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
So query will look like this:
User.createCriteria().list([max:params.max,offset:params.offset],{ resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); createAlias("others", "others", CriteriaSpecification.LEFT_JOIN); ilike("others.firstName", "%${query}%"); });