Difference between findAll, getAll and list in Grails

There are several ways to do the same with Grails.

Finds all instances of a domain class:

Book.findAll() Book.getAll() Book.list() 

Gets an instance of the domain class for the specified id:

 Book.findById(1) Book.get(1) 

When do you use each of them? Are there significant differences in performance?

+50
grails gorm
Jan 18 '12 at 9:33
source share
3 answers

getAll is an extended version of get that accepts multiple identifiers and returns List instances. The size of the list will be the same as the number of identifiers provided; any misses will result in null in this slot. See http://grails.org/doc/latest/ref/Domain%20Classes/getAll.html

findAll allows you to use HQL queries and supports pagination, but they are not limited to instances of the calling class, so I use executeQuery . See http://grails.org/doc/latest/ref/Domain%20Classes/findAll.html

List finds all instances and supports pagination. See http://grails.org/doc/latest/ref/Domain%20Classes/list.html

get retrieves one instance by id. It uses the instance cache, so multiple calls in the same Hibernate session will result in no more than one database call (for example, if the instance is in the second level cache and you enable it).

findById is a dynamic crawler like findByName , findByFoo , etc. In fact, it does not use the instance cache, but can be cached if query caching is enabled (as a rule, this is not a good idea). get should be preferred since its caching is much smarter; cached query results (even for one instance like this) are pessimistic cleared more often than you expected, but the instance cache should not be so pessimistic.

In one case, which I would use for findById , as a security check, combined with another property. For example, instead of retrieving an instance of CreditCard using CreditCard.get(cardId) , I would find the user who is currently logged in and use CreditCard.findByIdAndUser(cardId, user) . This assumes that CreditCard has a User user property. Thus, both properties must match, and this would block the hacker from accessing the card instance, since the card ID could match, but the user did not.

+86
Jan 18 '12 at 19:53
source share

Another difference between Domain.findByID (id) and Domain.get (id) is that if you use a sleep filter, you need to use Domain.findById (id). Domain.get (id) bypasses the filter.

+11
May 7, '13 at 19:25
source share

AFAIK, they are all identical

 Book.findAll() Book.getAll() Book.list() 

They will return the same results.

 Book.findById(1) Book.get(1) 

but get(id) will use the cache (if enabled), so findById(1) should be preferred

+4
Jan 18 '12 at 10:12
source share



All Articles