Junior — Middle
Can you tell about caching mechanisms in JPA and what types of caches it uses?
sobes.tech AI
Answer from AI
In JPA (Java Persistence API), caching is used to improve performance by reducing the number of database accesses. JPA uses two main levels of cache:
-
First-level cache
- This cache is associated with the EntityManager.
- It exists for the lifetime of the EntityManager and stores loaded entities.
- When the same entity is requested again within the same EntityManager, data is retrieved from the cache rather than the database.
- This cache is not configurable and is always enabled.
-
Second-level cache
- This cache is shared among multiple EntityManagers.
- It is optional and requires configuration (e.g., using cache providers like Ehcache, Infinispan, etc.).
- It allows caching of entities, collections, and queries across sessions.
Additionally, there are query caching mechanisms (Query Cache) that cache the results of JPQL or SQL queries.
Example of configuring Hibernate's second-level cache:
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
And an annotation for an entity:
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {
// fields and methods
}
Thus, caching in JPA helps reduce the load on the database and speeds up access to frequently used data.