Jakarta Persistence API provides a comprehensive framework for object-relational mapping, entity lifecycle management, and database operations in Java applications
Complete reference for second-level caching and entity locking strategies in Jakarta Persistence.
import jakarta.persistence.*;Manage the second-level cache.
/**
* Interface for second-level cache management
* @since 2.0
*/
public interface Cache {
boolean contains(Class cls, Object primaryKey);
void evict(Class cls, Object primaryKey);
void evict(Class cls);
void evictAll();
<T> T unwrap(Class<T> cls);
}
/**
* Specifies whether an entity should be cached
* @since 2.0
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface Cacheable {
boolean value() default true;
}
/**
* Cache retrieve mode
* @since 2.0
*/
public enum CacheRetrieveMode {
USE,
BYPASS
}
/**
* Cache store mode
* @since 2.0
*/
public enum CacheStoreMode {
USE,
BYPASS,
REFRESH
}
/**
* Shared cache mode
* @since 2.0
*/
public enum SharedCacheMode {
ALL,
NONE,
ENABLE_SELECTIVE,
DISABLE_SELECTIVE,
UNSPECIFIED
}Control optimistic and pessimistic locking.
/**
* Lock mode types
* @since 1.0
*/
public enum LockModeType {
READ,
WRITE,
OPTIMISTIC,
OPTIMISTIC_FORCE_INCREMENT,
PESSIMISTIC_READ,
PESSIMISTIC_WRITE,
PESSIMISTIC_FORCE_INCREMENT,
NONE
}
/**
* Pessimistic lock scope
* @since 2.0
*/
public enum PessimisticLockScope {
NORMAL,
EXTENDED
}Usage Example:
EntityManager em = emf.createEntityManager();
// Use cache
Cache cache = emf.getCache();
boolean inCache = cache.contains(User.class, 1L);
cache.evict(User.class, 1L);
cache.evictAll();
// Cache modes
Map<String, Object> props = new HashMap<>();
props.put("jakarta.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS);
props.put("jakarta.persistence.cache.storeMode", CacheStoreMode.REFRESH);
User user = em.find(User.class, 1L, props);
// Optimistic locking
em.getTransaction().begin();
User user = em.find(User.class, 1L, LockModeType.OPTIMISTIC);
user.setName("New Name");
em.getTransaction().commit();
// Pessimistic locking
em.getTransaction().begin();
User user = em.find(User.class, 1L, LockModeType.PESSIMISTIC_WRITE);
user.setName("New Name");
em.getTransaction().commit();
// Lock with timeout
Map<String, Object> lockProps = new HashMap<>();
lockProps.put("jakarta.persistence.lock.timeout", 5000);
lockProps.put("jakarta.persistence.lock.scope", PessimisticLockScope.EXTENDED);
em.lock(user, LockModeType.PESSIMISTIC_WRITE, lockProps);Install with Tessl CLI
npx tessl i tessl/maven-jakarta-persistence--jakarta-persistence-api