nicholas
nicholas

Reputation: 2762

Spring @Cacheable Not Working

I have a dao method annotate with @Cacheable but its cache not working at all. I put log message inside the method.

<cache:annotation-driven mode="proxy" proxy-target-class="true" cache-manager="cacheManager" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
        <property name="configLocation" value="WEB-INF/ehcache/ehcache.xml"></property>
        <property name="shared" value="true"></property>
    </bean>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache"></property>
    </bean>

@Controller
@RequestMapping(value = "/analytics")
public class AnalyticsController {

    @Autowired
    private ReportDao reportDao;

    /**
     * 
     */
    public AnalyticsController() {
    }

    @RequestMapping(value = "/lcr-report", method = RequestMethod.GET)
    public String viewCostReport(ModelMap map) {

        List<Country> countryList = reportDao.getAllCountry();

        map.put("countryList", countryList);

        return "lcrReport";
    }

}


@Repository
@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, 
    rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public class ReportDao {

    @Autowired
    private JdbcTemplate dao;

    /**
     * 
     */
    public ReportDao() {
    }

    @Cacheable(value = {"reportDao"}/*, key= "T(Country).hash(#List<Country>)"*/)
    @Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=true, 
            rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
    public List<Country> getAllCountry() {
        List<Country> countryList =  null;
        BeanPropertyRowMapper<Country> mapper = new BeanPropertyRowMapper<Country>(Country.class);
        PreparedStatementCreator psc = new GenericPreparedStatementCreator("select c.country_code as countryCode, c.name as countryName from country c");
        System.out.println("Not from cache");
        countryList = dao.query(psc, mapper);

        return countryList;
    }

}

Upvotes: 1

Views: 6763

Answers (1)

Michail Nikolaev
Michail Nikolaev

Reputation: 3775

You should create key by using parameters to method getAllCountry. In your case it is empty, so you can do like this:

@Transactional(readOnly = true)
@Cacheable(value = CACHE_NAME, key = "'countries'")

and check if it works using Map cache:

@Configuration
@EnableCaching(proxyTargetClass = true)
public class CacheProducer {

@Bean
public CacheManager cacheManager() {
        SimpleCacheManager result = new SimpleCacheManager();
        result.setCaches(Arrays.asList(new ConcurrentMapCache(DictionaryServiceImpl.CACHE_NAME)));
        return result;
    }
}

If it works - it is time to check your echache config.

Upvotes: 3

Related Questions