Java.Hibernate.Beginner.How do you enable second-level caching?

How do you enable second-level caching in Hibernate?

Answer:
Second-level cache is optional in Hibernate — to enable it, you need to:

🔹 1️⃣ Enable second-level cache globally
Add this property in your Hibernate configuration (e.g., hibernate.cfg.xml, application.properties, or application.yml):

hibernate.cache.use_second_level_cache=true

🔹 2️⃣ Choose and configure a cache provider
Hibernate doesn’t cache entities itself — it relies on an external cache provider like Ehcache, Infinispan, or Redis. You must:

  • Add the chosen provider’s dependency (e.g., Ehcache library) to your project.
  • Configure the provider (e.g., ehcache.xml for Ehcache).

🔹 3️⃣ Set the cache region factory
Specify the factory class for your provider:

hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

🔹 4️⃣ Mark entities as cacheable
Annotate each entity you want to store in the second-level cache with @Cacheable and the Hibernate-specific @Cache annotation to define the cache strategy:

@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {
    @Id
    private Long id;
    private String username;
}

🔹 Common concurrency strategies:

  • READ_ONLY – use for static, immutable data.
  • READ_WRITE – safe for most use cases, allows updates with proper synchronization.
  • NONSTRICT_READ_WRITE – fewer guarantees, better performance for rarely modified data.

🔹 5️⃣ (Optional) Configure query cache
If you also want to enable caching of query results:

hibernate.cache.use_query_cache=true

🔹 Summary of configuration in hibernate.cfg.xml:

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="hibernate.cache.region.factory_class">
      org.hibernate.cache.ehcache.EhCacheRegionFactory
    </property>
  </session-factory>
</hibernate-configuration>

Key takeaway:
To enable second-level cache, you must:
✅ Turn it on globally with hibernate.cache.use_second_level_cache=true,
✅ Choose and configure a provider,
✅ Mark individual entities with @Cacheable + @Cache.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.