javaspring-bootcaching

@Cacheable not working in SpringBoot project


I have the following code that technically should cache a lookup table. The Java compiler compiles fine and the program runs, however the dataset is not cached and it keeps doing a database lookup every time the method is called.

What do I need to do in order to enforce that once the database runs the dataset, that it does cache it and that the cache is referenced instead of continued database queries:


    @Cacheable(value = "eventTypes", key = "#p0")
    public List<EventType> getEventTypes() {

        String sql = "select * from event_types ";

        return jdbcTemplate.query(sql, new Object[] {},
                (rs, rowNum) -> EventType.builder()
                        .eventTypeId(rs.getLong("event_type_id"))
                        .description(rs.getString("description"))
                        .build()
        );

    }

As I note, I also have this in my application.properties file, which apparently is needed;

cache:
    cache-names:eventTypes,users

Solution

  • Following Spring documents (Official Spring Cache Docs):

    You need a valid configuration class:

    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableCaching
    public class CacheConfig {
        // your configuration for the cache
    }
    

    And then, wrap your code in a bean, like a component or a service layer:

    @Service
    public class YourService {
        
        @Cacheable(value = "eventTypes", key = "#p0")
        public List<EventType> getEventTypes() {
    
            String sql = "select * from event_types ";
    
            return jdbcTemplate.query(sql, new Object[] {},
                    (rs, rowNum) -> EventType.builder()
                            .eventTypeId(rs.getLong("event_type_id"))
                            .description(rs.getString("description"))
                            .build()
            );
    
        }
    
    }
    

    Ensure Spring Boot's spring-boot-starter-cache is in your pom or gradle file, without version (so SpringBoot parent can pick the correct version).

    For advanced configurations, refer to Spring's official documentation:

    documentation