Junior — Middle
Can you list the cache levels used in JPA?
sobes.tech AI
Answer from AI
JPA uses two main levels of caching:
-
First-level cache — this cache is associated with the EntityManager. It exists for the duration of a specific EntityManager and stores loaded entities. When the same entity is requested again within the same EntityManager, data is retrieved from this cache, improving performance.
-
Second-level cache — this cache is shared among multiple EntityManagers and sessions, typically implemented with external providers (e.g., Ehcache, Infinispan). It stores data between transactions and sessions, reducing the number of database accesses.
There is also:
- Query cache — caches the results of JPQL or SQL queries, so repeated queries with the same parameters can quickly return results without re-executing in the database.
Example of using second-level cache in Hibernate:
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {
@Id
private Long id;
private String name;
// getters and setters
}