Reputation: 6532
I am really new to spring caching.
I saw that spring caching annotations are based mostly on annotating methods.
My question is if i have a dao class that has the following method:
public User getUserById(long id);
And lets say i cache this method.
and have another dao method (with no annotation) like:
public void updateUser(User u);
Now imagine this scenario:
1) someone invokes the getUserById(user1Id); //(cache of size 1 now has user1)
2) someone else invokes the updateUser(User1) ; // lets say a simple name change
3) someone else invokes the getUserById(user1Id);
My question :
Assuming no other actions were taken, Will the 3rd invocation receives a deprecated data? (with the old name)?
If so , how to solve this simple use case?
Upvotes: 0
Views: 750
Reputation: 1916
You need to remove the stale items from cache. The Spring framework helps with several caching related annotations (you could annotate the update-method with @CacheEvict
for example). Spring has a good documentation on caching by the way.
Upvotes: 1
Reputation: 19020
Yes, the third invocation will return a stale data.
To overcome this, you should trigger a cache eviction after the update operation, by annotating your update method with a @CacheEvict
annotation:
@CacheEvict(value = "users", key = "#user.id")
void updateUser(User user) {
...
}
Where value = "users"
is the same cache name you had used for getUserById()
method, and User
class has an id
property of type Long (which is used as the users cache key)
Upvotes: 2