Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - How to get list of distinct User Objects

Tags:

grails

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.

like image 323
Ashish Joseph Avatar asked Jul 12 '13 09:07

Ashish Joseph


4 Answers

Ya projection is like filtering and selecting by username you should change it to

def criteria = User.createCriteria()
def users = criteria.listDistinct() {
    projections {
        groupProperty("username")
    }
}
return users

JOB DONE!

like image 161
Daniel Adenew Avatar answered Nov 11 '22 20:11

Daniel Adenew


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())
like image 20
zoran119 Avatar answered Nov 11 '22 20:11

zoran119


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}%");
    });
like image 33
Andrey Doloka Avatar answered Nov 11 '22 20:11

Andrey Doloka


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 }
like image 1
IgniteCoders Avatar answered Nov 11 '22 20:11

IgniteCoders