Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@cacheput is not updating the existing cache

I am working with Spring 4 and Hazelcast 3.2. I am trying to add a new record to existing cache with below code. somehow cache is not getting updated and at the same time I don't see any errors also. below is the code snippet for reference.

Note:- Cacheable is working fine, only cacheput is not working. Please throw light on this

@SuppressWarnings("unchecked")`enter code here`
    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    @Cacheable(value="user-role-data")
    public List<User> getUsersList() {
    // Business Logic
    List<User> users= criteriaQuery.list();

    }

@SuppressWarnings("unchecked")
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    @CachePut(value = "user-role-data")
    public User addUser(User user) {
                    return user;

    } 
like image 672
Somi Reddy Avatar asked Oct 15 '15 17:10

Somi Reddy


2 Answers

I had the same issue and managed to solved it. The issue seemed to be tied to the transaction management. Bascially updating the cache in the same method where you are creating or updating the new record does not work because the transaction was not committed. Here's how I solved it.

Service layer calls repo to insert user Then go back to service layer After the insert /update db call In the service layer I called a refresh cache method That returned the user data and this method has the cacheput annotation After that it worked.

like image 62
A_H Avatar answered Sep 16 '22 14:09

A_H


An alternative approach is you could use @CacheEvict(allEntries = true) on the method used to Save or Update or Delete the records. It will flush the existing cache.

Example:

@CacheEvict(allEntries = true) 
public void saveOrUpdate(Person person) 
{
     personRepository.save(person);
}

A new cache will be formed with updated result the next time you call a @Cacheable method

Example:

@Cacheable // caches the result of getAllPersons() method
public List<Person> getAllPersons() 
{
     return personRepository.findAll();
}
like image 41
Anantha Raju C Avatar answered Sep 19 '22 14:09

Anantha Raju C