4.2.3. Exception handling

If the EntityManager throws an exception (including any SQLException), you should immediately rollback the database transaction, call EntityManager.close() (if createEntityManager() has been called) and discard the EntityManager instance. Certain methods of EntityManager will not leave the persistence context in a consistent state. No exception thrown by an entity manager can be treated as recoverable. Ensure that the EntityManager will be closed by calling close() in a finally block. 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 EntityManager API are
  • 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
The 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.
Hibernate wraps 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 SQLException is always available via JDBCException.getCause(). Hibernate converts the SQLException into an appropriate JDBCException subclass using the SQLExceptionConverter attached to the SessionFactory. By default, the SQLExceptionConverter is defined by the configured dialect; however, it is also possible to plug in a custom implementation (see the javadocs for the SQLExceptionConverterFactory class for details). The standard JDBCException subtypes are:
  • 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.