grails-cache icon indicating copy to clipboard operation
grails-cache copied to clipboard

Add `unless` option to Cacheable

Open igoraguiar opened this issue 8 years ago • 4 comments

I have some cache conditions where the value can only be cached if the value is not null. Apparently there is now way to do it in version 4, since the result of the method call can not be accessed inside the condition closure.

Before, I had the following condition: "#result != null", now I would need to rewrite it to something like { result != null }

igoraguiar avatar Oct 18 '17 14:10 igoraguiar

I don't understand the use case. Can you put together a more concrete example?

jameskleeh avatar Oct 18 '17 14:10 jameskleeh

Of course. I have a service with a method like this:

@Cacheable(value = "dataServiceCache.vehicleByLabelAndCompanyId", condition = "#result != null") Vehicle findVehicleByLabelAndCompanyId(String label, long companyId) {

}

Now, with version 4, I have no way to do it using the condition closure. I don't want to cache null values because, in the exemple, the vehicle may be inserted at some point, and the method will continue to return null.

Also, IMHO, I think it should be nice to keep this kind of compatibility with the previous version.

igoraguiar avatar Oct 19 '17 13:10 igoraguiar

This could help with transitioning to newer versions of Grails that use ehcache 3. Version 2 allows null values, but 3 does not.

I think that Grails' Cacheable should try to follow Spring's. The solution would therefore be to add unless to mirror Spring's unless, in which "Unlike condition(), this expression is evaluated after the method has been called and can therefore refer to the result."

kgeis avatar Jun 06 '18 23:06 kgeis

The problem wasn't solved. If somebody came here with the same problem: solution that works for me is to override Ehcache.java file and add if(value == null) { putObserver.end(PutOutcome.NOOP); } Into put method

SleepingForester avatar Dec 26 '19 13:12 SleepingForester