groovygrailsgrails-orm

findBy when there could be more than one


I'm using a findBy query in a grails/gorm project, where there is usually only one result (and I only ever want one result). However, there could occasionally be two (or even three theoretically, though it hasn't happened yet). How can I tell GORM which one to return, when there are more than one? I'm looking these up by an ID in an external system, which will eventually roll back around when it hits a max, so we can have two rows in our data base for the same external ID. I will always want the most recent one.


My request:

Thing.findByExternalId(30)

in database, Thing table:

id,externalId,lastUpdated
1,30,{threeYearsAgo}
2,30,{aFewHoursAgo}

GORM is going to order these by ID by default, so I'm going to get the really old one if I don't tell it anything about how to order them. But I always want the more recent one. Can I tell GORM how to order a findBy query, so that the "first match" it returns is the one I want? Or do I have to do findAllBy, specify the order, and just use the first result? I can't find any documentation of an order feature in findBy, but perhaps I've missed something.

Thanks!


Solution

  • You can pass a second argument with a map to sort the results.

    See: https://gorm.grails.org/latest/hibernate/manual/index.html#_pagination_and_sorting

    E.g. Thing.findByExternalId(42, [sort: 'lastUpdated', order: 'desc'])