Search code examples
springspring-data-jpaspring-cache

@Cacheable for default spring data jpa methods without overriding them


Sry, if my question isn't new but i couldn't find answer.I use Spring Data JPA and Spring Cache. I have folowing repository

@CacheConfig(cacheNames = "Category")
@Cacheable
@Repository
public interface Repository extends CrudRepository<Category, Long> {

    Category findByCategory(String Category);
}

And i want to cache default CrudRepository methods, like findAll() and etc. It's work If i override them like this

    @CacheConfig(cacheNames = "Category")
    @Cacheable
    @Repository
    public interface Repository extends CrudRepository<Category, Long> {

        Category findByCategory(String Category);
        List<Category> findAll();

    }

But it's not convenient override them every time for every repository.

Is there a way cache defaults spring jpa methods without override them or no such way?


Solution

  • Yes, we can do it. Basically, Spring uses Hibernate ORM as the implementation of JPA. Hibernate itself supports caching functionality with it and will integrate better than Spring Cache.

    To enable L2 cache, add these properties to your project add the following properties.

    spring.jpa.properties.hibernate.cache.use_second_level_cache=true spring.jpa.properties.hibernate.cache.use_query_cache=true spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

    and dependencies hibernate-ehcache

    Once this is done, all your default methods of JPA like findOne(), findAll() will be cached.

    If you add any custom methods, you can add like below:

    @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") }) Category findByCategory(String Category);

    To test where default methods are cached, you can use the following properties to see if SQL has been executed.

    spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true