Grails Hibernate Filter findById(id) vs. get(id)
Asked Answered
I

1

5

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?

Ilke answered 13/8, 2015 at 12:32 Comment(6)
Could you post your error message here, please?Origami
IMHO and without your error message, I'd verify <id>'s dataType.Origami
I found it documented on the plugins page that get(<id>) is not working and that findById should be used instead. Can I Override the get(<id>) with my get(<id>) for all my domain classes.Ilke
Sure, but couldn't you post your error message here?Origami
sure what message? there is no error-message since there is no error. The Problem is that I am getting the domain Object which I shouldn't get.Ilke
I have for example a Domain Class 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
O
7

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.

Origami answered 13/8, 2015 at 19:56 Comment(1)
Thanks Victor for all your efforts. What I now did was replacing all my ".get(" with ".findById(" in all my controllers an checking each replacement manually.Ilke

© 2022 - 2024 — McMap. All rights reserved.