JPA Exceptions
Jakarta Persistence (JPA) defines a hierarchy of unchecked exceptions rooted in PersistenceException to handle runtime failures. This structure enables applications to catch specific errors or manage broad persistence issues by using the base class.
The exception hierarchy is as follows:
PersistenceException
├─ EntityExistsException
├─ EntityNotFoundException
├─ LockTimeoutException
├─ NoResultException
├─ NonUniqueResultException
├─ OptimisticLockException
├─ PessimisticLockException
├─ QueryTimeoutException
├─ RollbackException
├─ SchemaValidationException
└─ TransactionRequiredException General persistence exceptions
The base class for general persistence failures is:
This is the root runtime exception for the JPA API. All other JPA exceptions inherit from this class, enabling a single catch block to handle general persistence errors.
Transaction and lifecycle exceptions
These exceptions relate to transaction state and entity lifecycle operations:
Thrown when a transaction is required but is not active. This typically occurs when attempting to modify the database without an active transaction.
Thrown when the transaction is marked for rollback only or the commit fails. This exception often wraps an underlying cause.
Thrown when EntityManager.persist is called on an entity that already exists in the database.
Thrown when an entity is expected to exist but cannot be found. This commonly occurs during EntityManager.refresh or EntityManager.getReference calls.
Concurrency and locking exceptions
Lock acquisition failures during updates or retrieval are indicated by:
Thrown when an optimistic locking conflict occurs (for example, a version mismatch). This indicates that another transaction modified the entity since it was last read.
Thrown when a pessimistic lock cannot be obtained on a database row, often because of a deadlock or underlying database constraint.
Thrown when a request to acquire a lock times out. This can occur with both pessimistic and optimistic locking wait times.
Query exceptions
Exceptions specific to query execution and result retrieval:
Thrown by Query.getSingleResult() when the query returns no results.
Thrown by Query.getSingleResult() when the query returns more than one result.
Thrown when a query exceeds the specified timeout limit.
Schema exceptions
Exceptions related to database schema validation:
Thrown when the database schema does not match the expected entity mapping structure during validation.