Gorm: How to return a list of ids rather than objects

Sometimes you need to a list of object ids rather than full objects when using gorm. This can be the case when you want to process a list of matching objects, but have each one processed in its own transaction, rather than in a single larger transaction. An example of this is a non-transactional job that calls a service for each object. You don't want the object loaded in the job as its wasteful in both time and resources.

In order to do this you need to use projections in a criteria

List<String> getObjectIds() {
    def results = Object.withCriteria {
        Date now = new Date()
        or {
            isNull('lastIndexed')
            lt('lastIndexed', now - 7)
        }

        // the important bit... extract the ids of the object
        projections { property 'id' }
    }

    return results
}
  • You can use the withNewTransaction closure but you need to ensure you reload any objects you modify inside the closure when you come out of the closure.