In my Spring Boot 3 application that hosts an API I wanted to have some entries highly used but rarely changed entries in a second level cache. In the past I was usind hibernate-ehcache but that project seems to be dead. The replacement for it is hibernate-jcache.
First attempt was to use ehcache backing the jcache but this results in jaxb exceptions as usual. I already have redis in the system and thought about using it as second level cache. I found that redisson provides an implementation for this.
The following dependencies needed to be added to my gradle file:
implementation("org.hibernate.orm:hibernate-jcache")
// https://mvnrepository.com/artifact/org.redisson/redisson-hibernate-6
implementation("org.redisson:redisson-hibernate-6:3.20.0")
With this in place the application.yml was updated to use it (I only kept the relevant part in this post):
spring: jpa: ... properties: hibernate: ... cache: use_second_level_cache: true use_query_cache: true region: factory_class: org.redisson.hibernate.RedissonRegionFactory redisson: # not setting config path uses classpath /redisson.yaml # setting it requires a proper file path like shown below to use the same file # config: api/src/main/resources/redisson.yaml jakarta: persistence: sharedCache: mode: ENABLE_SELECTIVE
And by adding the following to the entities it already worked:
import jakarta.persistence.Cacheable @Entity ... @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class ... { ... }