Search code examples
spring-bootjpaspring-data-jpa

Enabling 2nd level cache in Spring JPA


Since managing sessions, transaction and other stuff is not required in Spring Data JPA unlike Hibernate, is there any way 2nd level caching can be enabled in Spring Data JPA? I tried google but it all takes me to articles of Hibernate (I understand that Hibernate works as a default spring JPA implementation but I don't understand if caching can be handled explicitly as it is done in Hibernate).

I am new to this topic.


Solution

  • There is no difference. So enable like Hibernate: Put the below in the application.properties:

    # Enable second-level cache
    spring.jpa.properties.hibernate.cache.use_second_level_cache=true
    
    # Specify the caching provider (Ehcache, Hazelcast, etc.)
    spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
    

    and below is your entity:

    @Entity
    @Cacheable
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class YourEntity {
        // Entity definition
    }