Caching
9. Caching
Section titled “9. Caching”Description:
- Hibernate provides a sophisticated caching system to improve application performance.
- It includes first-level cache (session cache), second-level cache (SessionFactory cache), and query cache. - Proper caching configuration can significantly reduce database round-trips and improve application responsiveness.
First Level Cache (Session Cache)
Section titled “First Level Cache (Session Cache)”Session session = sessionFactory.openSession();User user1 = session.get(User.class, 1L); // Hits databaseUser user2 = session.get(User.class, 1L); // Returns from cache - no database hitsession.close();Second Level Cache (SessionFactory Cache)
Section titled “Second Level Cache (SessionFactory Cache)”<!-- Enable second level cache --><property name="hibernate.cache.use_second_level_cache">true</property><property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>@Entity@Cacheable@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class Product { // entity fields}Query Cache
Section titled “Query Cache”<property name="hibernate.cache.use_query_cache">true</property>Query query = session.createQuery("FROM Product WHERE category = :category");query.setParameter("category", "electronics");query.setCacheable(true);List<Product> products = query.list();