Well, I found a specific explanation made by Burt for this question some years ago.
get()
(and read()
, which uses get()
and sets the instance to read-only) is the only method that always uses the 2nd-level cache. load()
will too but it's not mapped in GORM. All other methods are variants of criteria queries or HQL queries that support using the query cache (which is separate from the instance cache that get()
uses) but don't use it by default.
This is easy to test. Turn on basic sql logging in DataSource.groovy:
dataSource {
pooled = true
driverClassName = ...
...
loggingSql = true
}
and create a simple cached class:
class Thing {
String name
static mapping = {
cache true
}
}
Run grails console
and create an instance:
def thing = new Thing(name: 'foo').save()
then load it using findById() and note that repeated calls generate SQL each time:
println Thing.findById(1L).name
and load it using get() and note that only the 1st invocation generates SQL and repeated calls don't:
println Thing.get(1L).name
and you can then call findById()
again and it still hits the database each time even though that instance is cached."
And in my case, it works exactly like this.
<id>
's dataType. – OrigamiClass Person extends BaseDomainClass
I do this extends for all releveant Domain Class. My prefered workaouround to get around the get(<id>) would be override the get(<id>) in BaseDomainClass with findByID. – Ilke