4.2.3. Exception handling
EntityManagerthrows an exception (including any
SQLException), you should immediately rollback the database transaction, call
createEntityManager()has been called) and discard the
EntityManagerinstance. Certain methods of
EntityManagerwill not leave the persistence context in a consistent state. No exception thrown by an entity manager can be treated as recoverable. Ensure that the
EntityManagerwill be closed by calling
finallyblock. Note that a container managed entity manager will do that for you. You just have to let the RuntimeException propagate up to the container.
The Hibernate entity manager generally raises exceptions which encapsulate the Hibernate core exception. Common exceptions raised by the
- IllegalArgumentException: an argument is not permitted, not recognized, or in an incorrect format (or similar).
- EntityNotFoundException: an entity was expected but none match the requirement
- TransactionRequiredException: this operation has to be in a transaction
- IllegalStateException: the entity manager is used in a wrong way
HibernateException, which wraps most of the errors that can occur in a Hibernate persistence layer, is an unchecked exception. Note that Hibernate might also throw other unchecked exceptions which are not a
HibernateException. These are, again, not recoverable and appropriate action should be taken.
SQLExceptions thrown while interacting with the database in a
JDBCException. In fact, Hibernate will attempt to convert the exception into a more meningful subclass of
JDBCException. The underlying
SQLExceptionis always available via
JDBCException.getCause(). Hibernate converts the
SQLExceptioninto an appropriate
JDBCExceptionsubclass using the
SQLExceptionConverterattached to the
SessionFactory. By default, the
SQLExceptionConverteris defined by the configured dialect; however, it is also possible to plug in a custom implementation (see the javadocs for the
SQLExceptionConverterFactoryclass for details). The standard
JDBCConnectionException- indicates an error with the underlying JDBC communication.
SQLGrammarException- indicates a grammar or syntax problem with the issued SQL.
ConstraintViolationException- indicates some form of integrity constraint violation.
LockAcquisitionException- indicates an error acquiring a lock level necessary to perform the requested operation.
GenericJDBCException- a generic exception which did not fall into any of the other categories.