Count Records From A hasMany Relationship In Grails

Recently I was tasked with trying to determine a distinct count between two tables with a many-to-many and one-to-many relationship. More specifically I needed to find out how many users were signing into the system on any given day. This is not to be confused with how many logins a particular user had for any given day.

In the following example you’ll see two domain classes and a controller class. The User class represents all the users in my system. The username is unique and that is why I made it my primary key.

Again, I needed to figure out how many users signed into the server today using all the available GORM that Grails has to offer. In the controller, I created a new Date object and zeroed out the time because in my scenario it is not relevant. Then using withCriteria, I can create my own custom query without actually writing any SQL. The createAlias allows me to use the hasMany property that I defined in my domain class.

Doing a simple query was not good enough because that would produce an inaccurate count if I had multiple sign ins per day. I instead wanted a distinct count so regardless how many times someone signed in, it only registered once in this result because I don’t care how many times everyone signed in.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.