or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

caching-locking.mdcriteria-api.mdentity-manager.mdentity-mapping.mdindex.mdlifecycle-callbacks.mdmetamodel.mdqueries.mdspi.md
tile.json

tessl/maven-jakarta-persistence--jakarta-persistence-api

Jakarta Persistence API provides a comprehensive framework for object-relational mapping, entity lifecycle management, and database operations in Java applications

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/jakarta.persistence/jakarta.persistence-api@3.1.x

To install, run

npx @tessl/cli install tessl/maven-jakarta-persistence--jakarta-persistence-api@3.1.0

index.mddocs/

Jakarta Persistence API

Jakarta Persistence (JPA) is the industry-standard Java API for object-relational mapping (ORM). It provides a comprehensive framework for mapping Java objects to relational databases, managing entity lifecycles, performing queries, and handling transactions. JPA enables developers to work with databases using Java objects rather than SQL, while still providing full control when needed through native queries and stored procedures.

Package Information

  • Package Name: jakarta.persistence:jakarta.persistence-api
  • Package Type: maven
  • Language: Java
  • Version: 3.1.0
  • Java Version: Java 11 or higher
  • Installation:

Maven:

<dependency>
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <version>3.1.0</version>
</dependency>

Gradle:

implementation 'jakarta.persistence:jakarta.persistence-api:3.1.0'

Core Imports

import jakarta.persistence.*;
import jakarta.persistence.criteria.*;
import jakarta.persistence.metamodel.*;
import jakarta.persistence.spi.*;

For specific imports:

// Entity and mapping annotations
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

// Relationship annotations
import jakarta.persistence.OneToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;

// Entity manager and query interfaces
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;

// Criteria API
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;

Basic Usage

import jakarta.persistence.*;

// Define an entity
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 100)
    private String name;

    @Column(unique = true, nullable = false)
    private String email;

    // Getters and setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

// Use the entity
public class UserRepository {
    private EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("myPersistenceUnit");

    public void createUser() {
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            User user = new User();
            user.setName("Alice");
            user.setEmail("alice@example.com");

            em.persist(user);
            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }
            throw e;
        } finally {
            em.close();
        }
    }

    public User findUser(Long id) {
        EntityManager em = emf.createEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public void updateUser(Long id, String newName) {
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();
            User user = em.find(User.class, id);
            user.setName(newName);
            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }
            throw e;
        } finally {
            em.close();
        }
    }
}

Architecture

Jakarta Persistence is built around several key components:

  • Entity Model: Classes annotated with @Entity that map to database tables. Entities are managed Java objects with persistent identity.

  • EntityManager: The primary interface for interacting with the persistence context. It performs CRUD operations, executes queries, and manages entity lifecycle.

  • EntityManagerFactory: Factory for creating EntityManager instances. Thread-safe and typically created once per application.

  • Persistence Context: A set of managed entity instances. The EntityManager manages the persistence context and synchronizes it with the database.

  • JPQL (Jakarta Persistence Query Language): Object-oriented query language for querying entities. Similar to SQL but operates on entity objects rather than tables.

  • Criteria API: Type-safe, programmatic query construction API. Provides compile-time validation and refactoring safety.

  • Metamodel API: Provides access to the metadata of persistent entities. Used for type-safe criteria queries and introspection.

  • Lifecycle Callbacks: Annotations for hooking into entity lifecycle events (persist, update, remove, load).

  • SPI (Service Provider Interface): Allows persistence providers (like Hibernate, EclipseLink) to plug into the Jakarta Persistence framework.

Capabilities

Entity Mapping and Relationships

Define entities and their database mappings using annotations. Map Java classes to tables, fields to columns, and relationships between entities.

// Core entity annotation
@Target(TYPE)
@Retention(RUNTIME)
public @interface Entity {
    String name() default "";
}

// Table mapping
@Target(TYPE)
@Retention(RUNTIME)
public @interface Table {
    String name() default "";
    String catalog() default "";
    String schema() default "";
    UniqueConstraint[] uniqueConstraints() default {};
    Index[] indexes() default {};
}

// Primary key
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Id {
}

// Column mapping
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Column {
    String name() default "";
    boolean unique() default false;
    boolean nullable() default true;
    boolean insertable() default true;
    boolean updatable() default true;
    String columnDefinition() default "";
    String table() default "";
    int length() default 255;
    int precision() default 0;
    int scale() default 0;
}

// Primary key generation
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface GeneratedValue {
    GenerationType strategy() default GenerationType.AUTO;
    String generator() default "";
}

// Relationship annotations
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface OneToOne {
    Class targetEntity() default void.class;
    CascadeType[] cascade() default {};
    FetchType fetch() default FetchType.EAGER;
    boolean optional() default true;
    String mappedBy() default "";
    boolean orphanRemoval() default false;
}

@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface OneToMany {
    Class targetEntity() default void.class;
    CascadeType[] cascade() default {};
    FetchType fetch() default FetchType.LAZY;
    String mappedBy() default "";
    boolean orphanRemoval() default false;
}

@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface ManyToOne {
    Class targetEntity() default void.class;
    CascadeType[] cascade() default {};
    FetchType fetch() default FetchType.EAGER;
    boolean optional() default true;
}

@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface ManyToMany {
    Class targetEntity() default void.class;
    CascadeType[] cascade() default {};
    FetchType fetch() default FetchType.LAZY;
    String mappedBy() default "";
}

Entity Mapping and Relationships

Entity Manager Operations

Manage entity lifecycle, perform CRUD operations, and control persistence context.

/**
 * Interface for interacting with the persistence context
 */
public interface EntityManager extends AutoCloseable {
    /** Make an instance managed and persistent */
    void persist(Object entity);

    /** Merge the state of the given entity into the current persistence context */
    <T> T merge(T entity);

    /** Remove the entity instance */
    void remove(Object entity);

    /** Find by primary key */
    <T> T find(Class<T> entityClass, Object primaryKey);

    /** Find by primary key with properties */
    <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties);

    /** Find by primary key and lock */
    <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode);

    /** Find by primary key, lock, and properties */
    <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties);

    /** Get a reference to the entity */
    <T> T getReference(Class<T> entityClass, Object primaryKey);

    /** Synchronize the persistence context to the underlying database */
    void flush();

    /** Set the flush mode */
    void setFlushMode(FlushModeType flushMode);

    /** Get the flush mode */
    FlushModeType getFlushMode();

    /** Lock an entity instance */
    void lock(Object entity, LockModeType lockMode);

    /** Lock an entity instance with properties */
    void lock(Object entity, LockModeType lockMode, Map<String, Object> properties);

    /** Refresh the state of the instance from the database */
    void refresh(Object entity);

    /** Refresh with properties */
    void refresh(Object entity, Map<String, Object> properties);

    /** Refresh with lock mode */
    void refresh(Object entity, LockModeType lockMode);

    /** Refresh with lock mode and properties */
    void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties);

    /** Clear the persistence context */
    void clear();

    /** Remove the given entity from the persistence context */
    void detach(Object entity);

    /** Check if the instance is managed */
    boolean contains(Object entity);

    /** Get the lock mode for the entity */
    LockModeType getLockMode(Object entity);

    /** Get the properties and hints */
    Map<String, Object> getProperties();

    /** Set a property or hint */
    void setProperty(String propertyName, Object value);

    /** Create a query instance */
    Query createQuery(String qlString);

    /** Create a typed query instance */
    <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);

    /** Create a typed query from JPQL */
    <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);

    /** Create a native SQL query */
    Query createNativeQuery(String sqlString);

    /** Create a named query */
    Query createNamedQuery(String name);

    /** Create a typed named query */
    <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);

    /** Get the EntityManagerFactory */
    EntityManagerFactory getEntityManagerFactory();

    /** Get the CriteriaBuilder */
    CriteriaBuilder getCriteriaBuilder();

    /** Get the Metamodel */
    Metamodel getMetamodel();

    /** Get the EntityTransaction */
    EntityTransaction getTransaction();

    /** Join the current transaction */
    void joinTransaction();

    /** Check if joined to the current transaction */
    boolean isJoinedToTransaction();

    /** Get the EntityGraph */
    <T> EntityGraph<T> createEntityGraph(Class<T> rootType);

    /** Get a named EntityGraph */
    EntityGraph<?> createEntityGraph(String graphName);

    /** Get a named EntityGraph */
    EntityGraph<?> getEntityGraph(String graphName);

    /** Close the EntityManager */
    void close();

    /** Check if the EntityManager is open */
    boolean isOpen();

    /** Get the underlying provider object */
    Object getDelegate();

    /** Unwrap to provider-specific type */
    <T> T unwrap(Class<T> cls);
}

/**
 * Factory interface for EntityManager instances
 */
public interface EntityManagerFactory extends AutoCloseable {
    /** Create a new EntityManager */
    EntityManager createEntityManager();

    /** Create a new EntityManager with properties */
    EntityManager createEntityManager(Map map);

    /** Create EntityManager with synchronization type */
    EntityManager createEntityManager(SynchronizationType synchronizationType);

    /** Create EntityManager with synchronization type and properties */
    EntityManager createEntityManager(SynchronizationType synchronizationType, Map map);

    /** Get the CriteriaBuilder */
    CriteriaBuilder getCriteriaBuilder();

    /** Get the Metamodel */
    Metamodel getMetamodel();

    /** Check if factory is open */
    boolean isOpen();

    /** Close the factory */
    void close();

    /** Get properties and hints */
    Map<String, Object> getProperties();

    /** Get the Cache */
    Cache getCache();

    /** Get the PersistenceUnitUtil */
    PersistenceUnitUtil getPersistenceUnitUtil();

    /** Add a named query */
    void addNamedQuery(String name, Query query);

    /** Unwrap to provider-specific type */
    <T> T unwrap(Class<T> cls);

    /** Add a named entity graph */
    <T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph);
}

/**
 * Interface for resource-local entity transaction management
 */
public interface EntityTransaction {
    /** Start a transaction */
    void begin();

    /** Commit the transaction */
    void commit();

    /** Rollback the transaction */
    void rollback();

    /** Mark the transaction for rollback only */
    void setRollbackOnly();

    /** Check if transaction is marked for rollback */
    boolean getRollbackOnly();

    /** Check if transaction is active */
    boolean isActive();
}

Entity Manager Operations

Query Execution

Execute JPQL queries, native SQL queries, and stored procedures.

/**
 * Base query interface
 */
public interface Query {
    /** Execute a SELECT query and return the query results as a List */
    List getResultList();

    /** Execute a SELECT query that returns a single result */
    Object getSingleResult();

    /** Execute an UPDATE or DELETE statement */
    int executeUpdate();

    /** Set the maximum number of results to retrieve */
    Query setMaxResults(int maxResult);

    /** Get the maximum number of results */
    int getMaxResults();

    /** Set the position of the first result to retrieve */
    Query setFirstResult(int startPosition);

    /** Get the position of the first result */
    int getFirstResult();

    /** Set a query hint */
    Query setHint(String hintName, Object value);

    /** Get the hints */
    Map<String, Object> getHints();

    /** Bind a parameter value */
    Query setParameter(String name, Object value);

    /** Bind a positional parameter */
    Query setParameter(int position, Object value);

    /** Set the flush mode */
    Query setFlushMode(FlushModeType flushMode);

    /** Get the flush mode */
    FlushModeType getFlushMode();

    /** Set the lock mode */
    Query setLockMode(LockModeType lockMode);

    /** Get the lock mode */
    LockModeType getLockMode();

    /** Get the parameters */
    Set<Parameter<?>> getParameters();
}

/**
 * Typed query interface
 */
public interface TypedQuery<X> extends Query {
    /** Execute a SELECT query and return the query results as a typed List */
    List<X> getResultList();

    /** Execute a SELECT query that returns a single typed result */
    X getSingleResult();

    /** Set the maximum number of results */
    TypedQuery<X> setMaxResults(int maxResult);

    /** Set the position of the first result */
    TypedQuery<X> setFirstResult(int startPosition);

    /** Set a hint */
    TypedQuery<X> setHint(String hintName, Object value);

    /** Bind a parameter */
    TypedQuery<X> setParameter(String name, Object value);

    /** Bind a positional parameter */
    TypedQuery<X> setParameter(int position, Object value);

    /** Set the flush mode */
    TypedQuery<X> setFlushMode(FlushModeType flushMode);

    /** Set the lock mode */
    TypedQuery<X> setLockMode(LockModeType lockMode);
}

/**
 * Stored procedure query interface
 */
public interface StoredProcedureQuery extends Query {
    /** Register a stored procedure parameter */
    StoredProcedureQuery registerStoredProcedureParameter(int position, Class type, ParameterMode mode);

    /** Register a named parameter */
    StoredProcedureQuery registerStoredProcedureParameter(String parameterName, Class type, ParameterMode mode);

    /** Execute the stored procedure */
    boolean execute();

    /** Get the update count */
    int getUpdateCount();

    /** Check if more results exist */
    boolean hasMoreResults();

    /** Get the output parameter value */
    Object getOutputParameterValue(int position);

    /** Get the output parameter value by name */
    Object getOutputParameterValue(String parameterName);
}

Query Execution

Criteria API

Build type-safe queries programmatically.

/**
 * Main interface for constructing criteria queries
 */
public interface CriteriaBuilder {
    /** Create a CriteriaQuery object */
    CriteriaQuery<Object> createQuery();

    /** Create a typed CriteriaQuery */
    <T> CriteriaQuery<T> createQuery(Class<T> resultClass);

    /** Create a CriteriaUpdate query */
    <T> CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity);

    /** Create a CriteriaDelete query */
    <T> CriteriaDelete<T> createCriteriaDelete(Class<T> targetEntity);

    /** Create a conjunction (AND) predicate */
    Predicate and(Expression<Boolean> x, Expression<Boolean> y);

    /** Create a conjunction of predicates */
    Predicate and(Predicate... restrictions);

    /** Create a disjunction (OR) predicate */
    Predicate or(Expression<Boolean> x, Expression<Boolean> y);

    /** Create a disjunction of predicates */
    Predicate or(Predicate... restrictions);

    /** Create a negation predicate */
    Predicate not(Expression<Boolean> restriction);

    /** Create an equality predicate */
    Predicate equal(Expression<?> x, Expression<?> y);

    /** Create an equality predicate with value */
    Predicate equal(Expression<?> x, Object y);

    /** Create an inequality predicate */
    Predicate notEqual(Expression<?> x, Expression<?> y);

    /** Create a greater-than predicate */
    <Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> x, Expression<? extends Y> y);

    /** Create a less-than predicate */
    <Y extends Comparable<? super Y>> Predicate lessThan(Expression<? extends Y> x, Expression<? extends Y> y);

    /** Create an IS NULL predicate */
    Predicate isNull(Expression<?> x);

    /** Create an IS NOT NULL predicate */
    Predicate isNotNull(Expression<?> x);

    /** Create a LIKE predicate */
    Predicate like(Expression<String> x, Expression<String> pattern);

    /** Create a LIKE predicate with value */
    Predicate like(Expression<String> x, String pattern);
}

/**
 * Criteria query interface
 */
public interface CriteriaQuery<T> extends AbstractQuery<T> {
    /** Specify the select item */
    CriteriaQuery<T> select(Selection<? extends T> selection);

    /** Specify multiple select items */
    CriteriaQuery<T> multiselect(Selection<?>... selections);

    /** Create and add a query root */
    <X> Root<X> from(Class<X> entityClass);

    /** Add a WHERE clause */
    CriteriaQuery<T> where(Expression<Boolean> restriction);

    /** Add WHERE predicates */
    CriteriaQuery<T> where(Predicate... restrictions);

    /** Specify GROUP BY expressions */
    CriteriaQuery<T> groupBy(Expression<?>... grouping);

    /** Specify HAVING clause */
    CriteriaQuery<T> having(Expression<Boolean> restriction);

    /** Specify HAVING predicates */
    CriteriaQuery<T> having(Predicate... restrictions);

    /** Specify ORDER BY */
    CriteriaQuery<T> orderBy(Order... o);

    /** Specify DISTINCT */
    CriteriaQuery<T> distinct(boolean distinct);

    /** Get the query roots */
    Set<Root<?>> getRoots();
}

/**
 * Query root interface
 */
public interface Root<X> extends From<X, X> {
    /** Get the entity type */
    EntityType<X> getModel();
}

Criteria API

Metamodel API

Access entity metadata for type-safe queries and introspection.

/**
 * Provides access to the metamodel of persistent entities
 */
public interface Metamodel {
    /** Return the metamodel entity type */
    <X> EntityType<X> entity(Class<X> cls);

    /** Return the metamodel managed type */
    <X> ManagedType<X> managedType(Class<X> cls);

    /** Return the metamodel embeddable type */
    <X> EmbeddableType<X> embeddable(Class<X> cls);

    /** Get the managed types */
    Set<ManagedType<?>> getManagedTypes();

    /** Get the entity types */
    Set<EntityType<?>> getEntities();

    /** Get the embeddable types */
    Set<EmbeddableType<?>> getEmbeddables();
}

/**
 * Entity type interface
 */
public interface EntityType<X> extends IdentifiableType<X>, Bindable<X> {
    /** Get the entity name */
    String getName();
}

/**
 * Singular attribute interface
 */
public interface SingularAttribute<X, T> extends Attribute<X, T>, Bindable<T> {
    /** Check if attribute is an ID attribute */
    boolean isId();

    /** Check if attribute is a version attribute */
    boolean isVersion();

    /** Check if attribute is optional */
    boolean isOptional();

    /** Get the type */
    Type<T> getType();
}

/**
 * Plural attribute interface
 */
public interface PluralAttribute<X, C, E> extends Attribute<X, C>, Bindable<E> {
    /** Get the collection type */
    CollectionType getCollectionType();

    /** Get the element type */
    Type<E> getElementType();
}

Metamodel API

Lifecycle Callbacks

Hook into entity lifecycle events.

/**
 * Lifecycle callback annotations
 */
@Target({METHOD})
@Retention(RUNTIME)
public @interface PrePersist {
}

@Target({METHOD})
@Retention(RUNTIME)
public @interface PostPersist {
}

@Target({METHOD})
@Retention(RUNTIME)
public @interface PreUpdate {
}

@Target({METHOD})
@Retention(RUNTIME)
public @interface PostUpdate {
}

@Target({METHOD})
@Retention(RUNTIME)
public @interface PreRemove {
}

@Target({METHOD})
@Retention(RUNTIME)
public @interface PostRemove {
}

@Target({METHOD})
@Retention(RUNTIME)
public @interface PostLoad {
}

/**
 * Entity listeners annotation
 */
@Target({TYPE})
@Retention(RUNTIME)
public @interface EntityListeners {
    Class[] value();
}

/**
 * Exclude listeners annotations
 */
@Target({TYPE})
@Retention(RUNTIME)
public @interface ExcludeDefaultListeners {
}

@Target({TYPE})
@Retention(RUNTIME)
public @interface ExcludeSuperclassListeners {
}

Lifecycle Callbacks

Caching and Locking

Control second-level caching and entity locking strategies.

/**
 * Cache interface for second-level cache management
 */
public interface Cache {
    /** Check if entity is in cache */
    boolean contains(Class cls, Object primaryKey);

    /** Evict entity from cache */
    void evict(Class cls, Object primaryKey);

    /** Evict all entities of a class from cache */
    void evict(Class cls);

    /** Evict all entities from cache */
    void evictAll();

    /** Unwrap to provider-specific cache interface */
    <T> T unwrap(Class<T> cls);
}

/**
 * Lock mode enumeration
 */
public enum LockModeType {
    READ,
    WRITE,
    OPTIMISTIC,
    OPTIMISTIC_FORCE_INCREMENT,
    PESSIMISTIC_READ,
    PESSIMISTIC_WRITE,
    PESSIMISTIC_FORCE_INCREMENT,
    NONE
}

/**
 * Cache retrieve mode
 */
public enum CacheRetrieveMode {
    USE,
    BYPASS
}

/**
 * Cache store mode
 */
public enum CacheStoreMode {
    USE,
    BYPASS,
    REFRESH
}

/**
 * Cacheable annotation
 */
@Target({TYPE})
@Retention(RUNTIME)
public @interface Cacheable {
    boolean value() default true;
}

Caching and Locking

Service Provider Interface

Implement custom persistence providers and integrate with Jakarta Persistence.

/**
 * Interface implemented by persistence providers
 */
public interface PersistenceProvider {
    /** Create EntityManagerFactory */
    EntityManagerFactory createEntityManagerFactory(String emName, Map map);

    /** Create container EntityManagerFactory */
    EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map);

    /** Generate database schema */
    void generateSchema(PersistenceUnitInfo info, Map map);

    /** Generate schema by persistence unit name */
    boolean generateSchema(String persistenceUnitName, Map map);

    /** Get the ProviderUtil */
    ProviderUtil getProviderUtil();
}

/**
 * Persistence unit information interface
 */
public interface PersistenceUnitInfo {
    /** Get persistence unit name */
    String getPersistenceUnitName();

    /** Get persistence provider class name */
    String getPersistenceProviderClassName();

    /** Get transaction type */
    PersistenceUnitTransactionType getTransactionType();

    /** Get JTA data source */
    DataSource getJtaDataSource();

    /** Get non-JTA data source */
    DataSource getNonJtaDataSource();

    /** Get mapping file names */
    List<String> getMappingFileNames();

    /** Get JAR file URLs */
    List<URL> getJarFileUrls();

    /** Get persistence unit root URL */
    URL getPersistenceUnitRootUrl();

    /** Get managed class names */
    List<String> getManagedClassNames();

    /** Check if unlisted classes are excluded */
    boolean excludeUnlistedClasses();

    /** Get shared cache mode */
    SharedCacheMode getSharedCacheMode();

    /** Get validation mode */
    ValidationMode getValidationMode();

    /** Get properties */
    Properties getProperties();

    /** Get persistence XML schema version */
    String getPersistenceXMLSchemaVersion();

    /** Get class loader */
    ClassLoader getClassLoader();

    /** Add transformer */
    void addTransformer(ClassTransformer transformer);

    /** Get new temp class loader */
    ClassLoader getNewTempClassLoader();
}

Service Provider Interface

Enumerations and Constants

/**
 * Cascade type for relationship operations
 */
public enum CascadeType {
    ALL,
    PERSIST,
    MERGE,
    REMOVE,
    REFRESH,
    DETACH
}

/**
 * Fetch type for lazy or eager loading
 */
public enum FetchType {
    LAZY,
    EAGER
}

/**
 * Flush mode type
 */
public enum FlushModeType {
    COMMIT,
    AUTO
}

/**
 * Generation strategy for primary keys
 */
public enum GenerationType {
    TABLE,
    SEQUENCE,
    IDENTITY,
    UUID,
    AUTO
}

/**
 * Inheritance strategy
 */
public enum InheritanceType {
    SINGLE_TABLE,
    TABLE_PER_CLASS,
    JOINED
}

/**
 * Temporal type for date/time fields
 */
public enum TemporalType {
    DATE,
    TIME,
    TIMESTAMP
}

/**
 * Discriminator column type
 */
public enum DiscriminatorType {
    STRING,
    CHAR,
    INTEGER
}

/**
 * Enum mapping type
 */
public enum EnumType {
    ORDINAL,
    STRING
}

/**
 * Access type for entity fields
 */
public enum AccessType {
    FIELD,
    PROPERTY
}

/**
 * Parameter mode for stored procedures
 */
public enum ParameterMode {
    IN,
    INOUT,
    OUT,
    REF_CURSOR
}

/**
 * Persistence context type
 */
public enum PersistenceContextType {
    TRANSACTION,
    EXTENDED
}

/**
 * Synchronization type
 */
public enum SynchronizationType {
    SYNCHRONIZED,
    UNSYNCHRONIZED
}

/**
 * Shared cache mode
 */
public enum SharedCacheMode {
    ALL,
    NONE,
    ENABLE_SELECTIVE,
    DISABLE_SELECTIVE,
    UNSPECIFIED
}

/**
 * Validation mode
 */
public enum ValidationMode {
    AUTO,
    CALLBACK,
    NONE
}

/**
 * Pessimistic lock scope
 */
public enum PessimisticLockScope {
    NORMAL,
    EXTENDED
}

/**
 * Constraint mode
 */
public enum ConstraintMode {
    CONSTRAINT,
    NO_CONSTRAINT,
    PROVIDER_DEFAULT
}

Exception Hierarchy

/**
 * Base exception for persistence operations
 */
public class PersistenceException extends RuntimeException {
}

/**
 * Thrown when entity already exists during persist
 */
public class EntityExistsException extends PersistenceException {
}

/**
 * Thrown when entity is not found
 */
public class EntityNotFoundException extends PersistenceException {
}

/**
 * Thrown when no result is returned from getSingleResult
 */
public class NoResultException extends PersistenceException {
}

/**
 * Thrown when multiple results returned from getSingleResult
 */
public class NonUniqueResultException extends PersistenceException {
}

/**
 * Thrown on optimistic locking conflict
 */
public class OptimisticLockException extends PersistenceException {
    public Object getEntity();
}

/**
 * Thrown on pessimistic locking conflict
 */
public class PessimisticLockException extends PersistenceException {
    public Object getEntity();
}

/**
 * Thrown when lock timeout occurs
 */
public class LockTimeoutException extends PersistenceException {
    public Object getObject();
}

/**
 * Thrown when query execution times out
 */
public class QueryTimeoutException extends PersistenceException {
    public Query getQuery();
}

/**
 * Thrown when transaction is rolled back
 */
public class RollbackException extends PersistenceException {
}

/**
 * Thrown when transaction is required but not active
 */
public class TransactionRequiredException extends PersistenceException {
}