Reputation: 189
I've a Person
which has id
and name
.
When I search by Id
the method returned the Person
Object and I want to make name
as cache key but the returned data is not accessible in key
tag of Cacheable
annotation but the name
is accessible in unless
tag.
@Cacheable(value = "Cache", key = "#result.name", unless="#result.name == 'Foo'")
public Person getById(String id){}
If I use key = "#result.name"
it gives me exception :
EL1007E: Property or field 'name' cannot be found on null
What am I missing, How can I access returned data from method in key
tag?
Upvotes: 5
Views: 5463
Reputation: 1895
Cache keys should generated from method parameter on which you are applying caching and you cache result of method.
Working code will be:
@Cacheable(value = "personCache", key = "#id", unless="#person.name == 'Foo'")
public Person getById(String id){
Person person = data initialization logic here;
return person;
}
For more information on Caching go through this link.
For some best practice follow this blog.
Upvotes: 0
Reputation: 3364
In your use case this is not possible since the cache key gets generated from the parameter you're passing to the method and that's String id
. Therefore Spring tries to extract the name
parameter from the String. Which is not possible.
Even if it was possible to use the name of the result as cache key the cache wouldn't work as you're querying by id
.
Upvotes: 4