I have to calculate a “total” for each user based on individual actions — that is, a User hasMany Actions and each Action has a point. So I need to basically get a sum of all the points on all the actions.
Actions are added and subtracted regularly. Since this can be a rather heavy operation, it’s not feasible that I execute the “total” each time I need it. Therefore, I am thinking of running the operation once a day for each user and storing the total points on the User as an int.
Because I have thousands of users, I am trying to figure out the best way to do this. Should I basically iterate through all the users and call User.save() each time, or is there some kind of batch update mechanism I can use in Grails / GORM?
Is the model in your question your actual model, or a simplified version of it? If all you’re doing is User hasMany Actions and each Action has a point value (an integer?) that you’d like to sum up, that’s really the kind of thing that relational databases excel at. If you have the proper indexes on your database, I’d think this would be a very quick call, as long as you’re doing a groupBy query (or using grails projection criteria).
Here’s an example method that will take a list of users and will return an array that pairs user.id to the number of points that user currently has:
If desired, you could easily turn this into a map of user id to points for easier look-up:
If this really is slower than I’m thinking it is, you could use the executeUpdate with HQL similiar to what I have above to update a “totalPoints” field on each user (or keep it updated as part of a service whenever you add a new Action to that user).