Search code examples
grailsgrails-plugin

Grails Hibernate Filter findById(id) vs. get(id)


I am using hibernate Filter to filter my domain classes based on the login.

It is working as expected for

<DomainClass>.findById(<id>)

but it is not working for

<DomainClass>.get(<id>).

Why is the filter not used for get second version with get?


Solution

  • 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.