javaspring-bootsecond-level-cacheehcache-3

How can I set expiry on Second Level Cache?


Problem

I can't set expiry of second level cache with Ehcache.
Is there any way to config expiry?

My Codes

build.gradle

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.hibernate:hibernate-jcache:5.6.5.Final'
implementation 'org.ehcache:ehcache:3.9.9'

application.yml

spring:
  jpa:

    properties:
      javax:
        persistence:
          sharedCache:
            mode: ENABLE_SELECTIVE   # Enable caches only @Cacheable annotated classes
      hibernate:
        cache:
          use_query_cache: true
          use_second_level_cache: true
          region:
            factory_class: org.hibernate.cache.jcache.JCacheRegionFactory

My Entity

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Cacheable
@Cache(region = "test_cache", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Test {
.
.
.
}

Solution

  • Yes, there is a way.

    1. Change your factory_class to org.hibernate.cache.ehcache.EhCacheRegionFactory
    2. Create an ehcache.xml in /src/main/resources with this content:
       ...
       <cache-template name="default">
          <expiry>
             <ttl unit="hours">48</ttl>
          </expiry>
        </cache-template>
       ...
    

    Details to the XML configuration can be found at https://www.ehcache.org/documentation/3.9/xml.html