With Grails there are several ways to do the same thing.
Finds all of domain class instances:
Book.findAll()
Book.getAll()
Book.list()
Retrieves an instance of the domain class for the specified id:
Book.findById(1)
Book.get(1)
When do you use each one? Are there significant differences in performance?
Another difference between Domain.findByID(id) and Domain.get(id) is that if you're using a hibernate filter, you need to use Domain.findById(id). Domain.get(id) bypasses the filter.
AFAIK, these are all identical
These will return the same results
but
get(id)
will use the cache (if enabled), so should be preferred tofindById(1)
getAll
is an enhanced version ofget
that takes multiple ids and returns aList
of instances. The list size will be the same as the number of provided ids; any misses will result in anull
at that slot. See http://grails.org/doc/latest/ref/Domain%20Classes/getAll.htmlfindAll
lets you use HQL queries and supports pagination, but they're not limited to instances of the calling class so I useexecuteQuery
instead. See http://grails.org/doc/latest/ref/Domain%20Classes/findAll.htmllist
finds all instances and supports pagination. See http://grails.org/doc/latest/ref/Domain%20Classes/list.htmlget
retrieves a single instance by id. It uses the instance cache, so multiple calls within the same Hibernate session will result in at most one database call (e.g. if the instance is in the 2nd-level cache and you've enabled it).findById
is a dynamic finder, likefindByName
,findByFoo
, etc. As such it does not use the instance cache, but can be cached if you have query caching enabled (typically not a good idea).get
should be preferred since its caching is a lot smarter; cached query results (even for a single instance like this) are pessimistically cleared more often than you would expect, but the instance cache doesn't need to be so pessimistic.The one use case I would have for
findById
is as a security-related check, combined with another property. For example instead of retrieving aCreditCard
instance usingCreditCard.get(cardId)
, I'd find the currently logged-in user and useCreditCard.findByIdAndUser(cardId, user)
. This assumes thatCreditCard
has aUser user
property. That way both properties have to match, and this would block a hacker from accessing the card instance since the card id might match, but the user wouldn't.