Search code examples
hibernategrailshqlgrails-orm

Count length of hasMany property


I have a domain class:

class Person{
 static hasMany = [friends:Person]
 ....
}

What I'm looking to do is to filter out Persons based on the number of friends they have.

This is what I came up with, and it does the job:

Person.where{
 friends.size() == 3
}

It's slow as hell and I could do without the list, so ideally I'd just like to run something like:

select count(*) from Person where size(friends) == 3

I've searched like a maniac but I can't find that much information on countBy (I guess what I'm trying to do is countWhere).

Any input is appreciated.


Solution

  • With a where query, you should be able to use count() instead of listing all the matches. where creates a DetachedCriteria that supports a number of operations.

    Person.where { friends.size() == 3 }.count()
    

    If that doesn't work as well as I think it should, you might need to use a Criteria with a projection to only return the count.

    Person.withCriteria {
        sizeEq 'friends', 3
        projections {
            rowCount()
        }
    }