Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Spring's @CachePut annotation work with a void return type?

I am attempting to implement caching in my application using Ehcache and the Spring 3.1 built in caching annotations (@Cacheable, @CacheEvict, and @CachePut).

I have created a cache as follows:

@Cacheable(value = "userCache", key = "#user.id")
public List<User> getAllUsers() {
...
}

I am attempting to update this cache with a new value using the @CachePut annotation as below:

@CachePut(value = "userCache", key = "#user.id")
public void addUser(User user) {
...
}

However, the new "User" is not being added to the cache. Is this because of the void return type?

like image 760
elpisu Avatar asked Jul 30 '13 11:07

elpisu


People also ask

How does @cachable work?

As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.

Which is the spring boot annotation used for caching auto configuration?

Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation.


2 Answers

Yes, it's because void return type. The @CachePut annotation places the result of method into the cache. In your case there is no result so nothing is put to the cache.

Change method signature to return User:

public User addUser(User user) { 
   ...
}
like image 151
ragnor Avatar answered Nov 15 '22 07:11

ragnor


This wont work , cause you are using same cache value "userCache" but return type of method getAllUsers is List and return type of addUser is User. which will create inconsistency in data that have been stored in cache.

( List + User ) : this type of data will be formed in cache.

And later when you will call method getAllUsers , code will be

List userList = getAllUsers();

But in this case , data will be fetched from cache and throw "Class cast Exception".

As , ( List + User ) can not be cast in to List.

Is there any solution to this? I am stuck with this and don't know how to proceed. Will using custom annotations work here?

like image 34
user3667945 Avatar answered Nov 15 '22 08:11

user3667945