1. Introduction

In this tutorial, we’ll discuss some common exceptions we can encounter while working with Hibernate.

We’ll review their purpose and some common causes. Additionally, we’ll look into their solutions.

2. Hibernate Exception Overview

Many conditions can cause exceptions to be thrown while using Hibernate. These can be mapping errors, infrastructure problems, SQL errors, data integrity violations, session problems, and transaction errors.

*These exceptions mostly extend from HibernateException.* However, if we’re using Hibernate as a JPA persistence provider, these exceptions may get wrapped into PersistenceException.

Both of these base classes extend from RuntimeException. Therefore, they’re all unchecked. Hence, we don’t need to catch or declare them at every place they’re used.

Furthermore, most of these are unrecoverable. As a result, retrying the operation would not help. This means we have to abandon the current session on encountering them.

Let’s now look into each of these, one at a time.

3. Mapping Errors

Object-Relational mapping is a major benefit of Hibernate. Specifically, it frees us from manually writing SQL statements.

At the same time, it requires us to specify the mapping between Java objects and database tables. Accordingly, we specify them using annotations or through mapping documents. These mappings can be coded manually. Alternatively, we can use tools to generate them.

While specifying these mappings, we may make mistakes. These could be in the mapping specification. Or, there can be a mismatch between a Java object and the corresponding database table.

Such mapping errors generate exceptions. We come across them frequently during initial development. Additionally, we may run into them while migrating changes across environments.

Let’s look into these errors with some examples.

3.1. MappingException

A problem with the object-relational mapping causes a MappingException to be thrown:

    public void whenQueryExecutedWithUnmappedEntity_thenMappingException() {
        thrown.expect(isA(MappingException.class));
        thrown.expectMessage("Unable to locate persister: com.baeldung.hibernate.exception.ProductNotMapped");

        ProductNotMapped product = new ProductNotMapped();
        product.setId(1);
        product.setName("test");

        Session session = sessionFactory.openSession();
        session.save(product);
    }

In the above code, when you try to persist a class that is not defined as entity it will throw a Mapping Exception*.*

However, the ProductNotMapped class doesn’t have any mapping specified. Therefore, Hibernate doesn’t know the structure of that class, how are the columns and throws the exception.

For a detailed analysis of possible causes and solutions, check out Hibernate Mapping Exception – Unknown Entity.

Similarly, other errors can also cause this exception:

  • Mixing annotations on fields and methods
  • Failing to specify the @JoinTable for a @ManyToMany association
  • The default constructor of the mapped class throws an exception during mapping processing

Furthermore, MappingException has a few subclasses that can indicate specific mapping problems:

  • AnnotationException – a problem with an annotation
  • DuplicateMappingException – duplicate mapping for a class, table, or property name
  • InvalidMappingException – mapping is invalid
  • MappingNotFoundException – mapping resource could not be found
  • PropertyNotFoundException – an expected getter or setter method could not be found on a class

Therefore, if we come across this exception, we should first verify our mappings.

3.2. AnnotationException

To understand the AnnotationException, let’s create an entity without an identifier annotation on any field or property:

@Entity
public class EntityWithNoId {
    private int id;
    public int getId() {
        return id;
    }

    // standard setter
}

Since Hibernate expects every entity to have an identifier, we’ll get an HibernateException when we use the entity:

    public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
        thrown.expect(isA(HibernateException.class));
        thrown.expectMessage("Entity 'com.baeldung.hibernate.exception.EntityWithNoId' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)");

        Configuration cfg = getConfiguration();
        cfg.addAnnotatedClass(EntityWithNoId.class);
        cfg.buildSessionFactory();
    }

Furthermore, some other probable causes are:

  • Unknown sequence generator used in the @GeneratedValue annotation
  • @Temporal annotation used with a Java 8 Date/Time class
  • Target entity missing or non-existent for @ManyToOne or @OneToMany
  • Raw collection classes used with relationship annotations @OneToMany or @ManyToMany
  • Concrete classes used with the collection annotations @OneToMany, @ManyToMany or @ElementCollection as Hibernate expects the collection interfaces

To resolve this exception, we should first check the specific annotation mentioned in the error message.

3.3. QuerySyntaxException

Before diving deep into the details, let’s try to understand what the exception means.

QuerySyntaxException, as the name indicates, tells us that the specified query has invalid syntax.

The most typical cause of this exception is using the table name instead of the class name in HQL queries.

For instance, let’s consider the Product entity:

import jakarta.persistence.Entity;
import jakarta.persistence.Table;

@Entity
@Table(name = "PRODUCT")
public class Product {

    private int id;
    private String name;
    private String description;

    // Getters and setters
}

@Entity denotes that the annotated class is an entity. It tells us that this class represents a table stored in a database.

Typically, the table name may be different from the entity name. So, that’s where @Table comes to the rescue. It allows us to specify the exact name of the table in the database.

Now, let’s exemplify the exception using a test case:

    @Test
    public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() {
        thrown.expectCause(isA(UnknownEntityException.class));
        thrown.expectMessage("Could not resolve root entity 'PRODUCT");

        Session session = sessionFactory.openSession();
        List<Product> results = session.createQuery("from PRODUCT", Product.class)
            .getResultList();
    }

As we can see, Hibernate fails with UnknowEntityException because we used PRODUCT instead of Product in our query*.* In other words, we must use the entity name and not the table name in our query.

4. Schema Management Errors

Automatic database schema management is another benefit of Hibernate. For example, it can generate DDL statements to create or validate database objects.

To use this feature, we need to set the hibernate.hbm2ddl.auto property appropriately.

If there are problems while performing schema management, we get an exception. Let’s examine these errors.

4.1. SchemaManagementException

Any infrastructure-related problem in performing schema management causes a SchemaManagementException.

To demonstrate, let’s instruct Hibernate to validate the database schema:

public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() {
    thrown.expect(SchemaManagementException.class);
    thrown.expectMessage("Schema-validation: missing table");

    Configuration cfg = getConfiguration();
    cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate");
    cfg.addAnnotatedClass(Product.class);
    cfg.buildSessionFactory();
}

Since the table corresponding to Product is not present in the database, we get the schema-validation exception while building the SessionFactory.

Additionally, there are other possible scenarios for this exception:

  • unable to connect to the database to perform schema management tasks
  • the schema is not present in the database

4.2. CommandAcceptanceException

Any problem executing a DDL corresponding to a specific schema management command can cause a CommandAcceptanceException.

As an example, let’s specify the wrong dialect while setting up the SessionFactory:

public void whenWrongDialectSpecified_thenCommandAcceptanceException() {
    thrown.expect(SchemaManagementException.class);
    thrown.expectCause(isA(CommandAcceptanceException.class));
    thrown.expectMessage("Halting on error : Error executing DDL");

    Configuration cfg = getConfiguration();
    cfg.setProperty(AvailableSettings.DIALECT,
      "org.hibernate.dialect.MySQLDialect");
    cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update");
    cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true");
    cfg.getProperties()
      .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true);

    cfg.addAnnotatedClass(Product.class);
    cfg.buildSessionFactory();
}

Here, we’ve specified the wrong dialect: MySQLDialect. Also, we’re instructing Hibernate to update the schema objects. Consequently, the DDL statements executed by Hibernate to update the H2 database will fail and we’ll get an exception.

By default, Hibernate silently logs this exception and moves on. When we later use the SessionFactory, we get the exception.

To ensure that an exception is thrown on this error, we’ve set the property HBM2DDL_HALT_ON_ERROR to true.

Similarly, these are some other common causes for this error:

  • There is a mismatch in column names between mapping and the database
  • Two classes are mapped to the same table
  • The name used for a class or table is a reserved word in the database, like USER, for example
  • The user used to connect to the database does not have the required privilege

5. SQL Execution Errors

When we insert, update, delete or query data using Hibernate, it executes DML statements against the database using JDBC. This API raises an SQLException if the operation results in errors or warnings.

Hibernate converts this exception into JDBCException or one of its suitable subclasses:

  • ConstraintViolationException
  • DataException
  • JDBCConnectionException
  • LockAcquisitionException
  • PessimisticLockException
  • QueryTimeoutException
  • SQLGrammarException
  • GenericJDBCException

Let’s discuss common errors.

5.1. JDBCException

JDBCException is always caused by a particular SQL statement. We can call the getSQL method to get the offending SQL statement.

Furthermore, we can retrieve the underlying SQLException with the getSQLException method.

5.2. SQLGrammarException

SQLGrammarException indicates that the SQL sent to the database was invalid. It could be due to a syntax error or an invalid object reference.

For example, a missing table can result in this error while querying data:

    @Test
    public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
        thrown.expectCause(isA(SQLGrammarException.class));
        thrown.expectMessage("could not prepare statement");

        Session session = sessionFactory.openSession();
        NativeQuery<Product> query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class);
        query.getResultList();
    }

Also, we can get this error while saving data if the table is missing:

public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
    thrown.expectCause(isA(SQLGrammarException.class));
    thrown.expectMessage("could not prepare statement");

    Configuration cfg = getConfiguration();
    cfg.addAnnotatedClass(Product.class);

    SessionFactory sessionFactory = cfg.buildSessionFactory();
    Session session = null;
    Transaction transaction = null;
    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        Product product = new Product();
        product.setId(1);
        product.setName("Product 1");
        session.save(product);
        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
        closeSessionFactoryQuietly(sessionFactory);
    }
}

Some other possible causes are:

  • The naming strategy used doesn’t map the classes to the correct tables
  • The column specified in @JoinColumn doesn’t exist

5.3. ConstraintViolationException

A ConstraintViolationException indicates that the requested DML operation caused an integrity constraint to be violated. We can get the name of this constraint by calling the getConstraintName method.

A common cause of this exception is trying to save duplicate records:

public void whenDuplicateIdSaved_thenConstraintViolationException() {
    thrown.expectCause(isA(ConstraintViolationException.class));
    thrown.expectMessage("could not execute statement");

    Session session = null;
    Transaction transaction = null;

    for (int i = 1; i <= 2; i++) {
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();
            Product product = new Product();
            product.setId(1);
            product.setName("Product " + i);
            session.save(product);
            transaction.commit();
        } catch (Exception e) {
            rollbackTransactionQuietly(transaction);
            throw (e);
        } finally {
            closeSessionQuietly(session);
        }
    }
}

Also, saving a null value to a NOT NULL column in the database can raise this error.

In order to resolve this error, we should perform all validations in the business layer. Furthermore, database constraints should not be used to do application validations.

5.4. DataException

DataException indicates that the evaluation of an SQL statement resulted in some illegal operation, type mismatch, or incorrect cardinality.

For instance, using character data against a numeric column can cause this error:

public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
    thrown.expectCause(isA(DataException.class));
    thrown.expectMessage("could not prepare statement");

    Session session = sessionFactory.getCurrentSession();
    NativeQuery<Product> query = session.createNativeQuery(
      "select * from PRODUCT where id='wrongTypeId'", Product.class);
    query.getResultList();
}

To fix this error, we should ensure that the data types and length match between the application code and the database.

5.5. IdentifierGenerationException

Typically, this exception is thrown when Hibernate fails to generate a valid value for the identifier of the entity class.

IdentifierGenerationException indicates that there is no value assigned to the field marked with the @Id annotation.

The most typical cause of this exception is passing an entity object with a null identifier to the save() method.

For instance, let’s consider the ProductEntity entity:

@Entity
@Table(name = "PRODUCT")
public class ProductEntity {

    @Id
    private Integer id;
    private String name;
    private String description;

    // Getters and Setters

}

@Id denotes that the annotated field is an identifier. It means that the field Id represents the primary key of the mapped table.

As we can see, we didn’t specify the generation strategy for the values of the identifier Id using @GeneratedValue.

Now, let’s illustrate the exception using a test case:

@Test
public void givenEntityWithoutId_whenCallingSave_thenThrowIdentifierGenerationException() {

    thrown.expect(isA(IdentifierGenerationException.class));
    thrown.expectMessage("ids for this class must be manually assigned before calling save(): com.baeldung.hibernate.exception.Product");

    Session session = null;
    Transaction transaction = null;

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        ProductEntity product = new ProductEntity();
        product.setName("Product Name");

        session.save(product);
        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
    }

}

As shown above, Hibernate fails with IdentifierGenerationException because we tried to save an entity instance that has a null value for the identifier*.*

So, to avoid this exception, we need to make sure that our identifier has a valid value.

*To do so, we can specify an ID generation strategy using @GeneratedValue. Otherwise, we need to set the value of the identifier manually before calling save().*

5.6. JDBCConnectionException

A JDBCConectionException indicates problems communicating with the database.

For example, a database or network going down can cause this exception to be thrown.

Additionally, an incorrect database setup can cause this exception. One such case is the database connection being closed by the server because it was idle for a long time. This can happen if we’re using connection pooling and the idle timeout setting on the pool is more than the connection timeout value in the database.

To solve this problem, we should first ensure that the database host is present and that it’s up. Then, we should verify that the correct authentication is used for the database connection. Finally, we should check that the timeout value is correctly set on the connection pool.

5.7. QueryTimeoutException

When a database query times out, we get this exception. We can also see it due to other errors, such as the tablespace becoming full.

This is one of the few recoverable errors, which means that we can retry the statement in the same transaction.

To fix this issue, we can increase the query timeout for long-running queries in multiple ways:

  • Set the timeout element in a @NamedQuery or @NamedNativeQuery annotation
  • Invoke the setHint method of the Query interface
  • Call the setTimeout method of the Transaction interface
  • Invoke the setTimeout method of the Query interface

Let’s now look into errors due to Hibernate session usage errors.

6.1. NonUniqueObjectException

Hibernate doesn’t allow two objects with the same identifier in a single session.

If we try to associate two instances of the same Java class with the same identifier in a single session, we get a NonUniqueObjectException. We can get the name and identifier of the entity by calling the getEntityName() and getIdentifier() methods.

To reproduce this error, let’s try to save two instances of Product with the same id with a session:

public void 
givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() {
    thrown.expect(isA(NonUniqueObjectException.class));
    thrown.expectMessage(
      "A different object with the same identifier value was already associated with the session");

    Session session = null;
    Transaction transaction = null;

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        Product product = new Product();
        product.setId(1);
        product.setName("Product 1");
        session.save(product);

        product = new Product();
        product.setId(1);
        product.setName("Product 2");
        session.save(product);

        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
    }
}

We’ll get a NonUniqueObjectException, as expected.

This exception occurs frequently while reattaching a detached object with a session by calling the update method. If the session has another instance with the same identifier loaded, then we get this error. In order to fix this, we can use the merge method to reattach the detached object.

6.2. StaleStateException

Hibernate throws StaleStateExceptions when the version number or timestamp check fails. It indicates that the session contained stale data.

Sometimes this gets wrapped into an OptimisticLockException.

This error usually happens while using long-running transactions with versioning.

In addition, it can also happen while trying to update or delete an entity if the corresponding database row doesn’t exist:

    @Test
    public void whenUpdatingNonExistingObject_thenStaleStateException() {
        thrown.expectCause(isA(StaleStateException.class));
        thrown.expectMessage("Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update PRODUCT set description=?, name=? where id=?");

        Session session = null;
        Transaction transaction = null;

        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            Product product1 = new Product();
            product1.setId(15);
            product1.setName("Product1");
            session.update(product1);
            transaction.commit();
        } catch (Exception e) {
            rollbackTransactionQuietly(transaction);
            throw (e);
        } finally {
            closeSessionQuietly(session);
        }
    }

Some other possible scenarios are:

  • we did not specify a proper unsaved-value strategy for the entity
  • two users tried to delete the same row at almost the same time
  • we manually set a value in the autogenerated ID or version field

7. Lazy Initialization Errors

We usually configure associations to be loaded lazily to improve application performance. The associations are fetched only when they’re first used.

However, Hibernate requires an active session to fetch data. If the session is already closed when we try to access an uninitialized association, we get an exception.

Let’s look into this exception and the various ways to fix it.

7.1. LazyInitializationException

LazyInitializationException indicates an attempt to load uninitialized data outside an active session. We can get this error in many scenarios.

First, we can get this exception while accessing a lazy relationship in the presentation layer. The reason is that the entity was partially loaded in the business layer and the session was closed.

Secondly, we can get this error with Spring Data if we use the getOne method. This method lazily fetches the instance.

There are many ways to solve this exception.

First of all, we can make all relationships eagerly loaded. But, this would impact the application performance because we’ll be loading data that won’t be used.

Secondly, we can keep the session open until the view is rendered. This is known as the “Open Session in View” and it’s an anti-pattern. We should avoid this as it has several disadvantages.

Thirdly, we can open another session and reattach the entity to fetch the relationships. We can do so by using the merge method on the session.

Finally, we can initialize the required associations in the business layers. We’ll discuss this in the next section.

7.2. Initializing Relevant Lazy Relationships in the Business Layer

There are many ways to initialize lazy relationships.

One option is to initialize them by invoking the corresponding methods on the entity. In this case, Hibernate will issue multiple database queries causing degraded performance. We refer to it as the “N+1 SELECT” problem.

Secondly, we can use Fetch Join to get the data in a single query. However, we need to write custom code to achieve this.

Finally, we can use entity graphs to define all the attributes to be fetched. We can use the annotations @NamedEntityGraph, @NamedAttributeNode, and @NamedEntitySubgraph to declaratively define the entity graph. We can also define them programmatically with the JPA API. Then, we retrieve the entire graph in a single call by specifying it in the fetch operation.

8. Transaction Issues

Transactions define units of work and isolation between concurrent activities. We can demarcate them in two different ways. First, we can define them declaratively using annotations. Second, we can manage them programmatically using the Hibernate Transaction API.

Furthermore, Hibernate delegates the transaction management to a transaction manager. If a transaction could not be started, committed, or rolled back due to any reason, Hibernate throws an exception.

We usually get a TransactionException or an IlegalStateException depending on the transaction manager.

As an illustration, let’s try to commit a transaction that has been marked for rollback:

    @Test
    public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() {
        thrown.expect(isA(IllegalStateException.class));
        thrown.expectMessage("Transaction already active");

        Session session = null;
        Transaction transaction = null;
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            Product product1 = new Product();
            product1.setId(15);
            product1.setName("Product1");
            session.save(product1);
            transaction = session.beginTransaction();
            transaction.setRollbackOnly();

            transaction.commit();
        } catch (Exception e) {
            rollbackTransactionQuietly(transaction);
            throw (e);
        } finally {
            closeSessionQuietly(session);
        }
    }

Similarly, other errors can also cause an exception:

  • Mixing declarative and programmatic transactions
  • Attempting to start a transaction when another one is already active in the session
  • Trying to commit or rollback without starting a transaction
  • Trying to commit or rollback a transaction multiple times

9. Concurrency Issues

Hibernate supports two locking strategies to prevent database inconsistency due to concurrent transactions – optimistic and pessimistic. Both of them raise an exception in case of a locking conflict.

To support high concurrency and high scalability, we typically use optimistic concurrency control with version checking. This uses version numbers or timestamps to detect conflicting updates.

OptimisticLockingException is thrown to indicate an optimistic locking conflict. For instance, we get this error if we perform two updates or deletes of the same entity without refreshing it after the first operation:

public void whenDeletingADeletedObject_thenOptimisticLockException() {
    thrown.expect(isA(OptimisticLockException.class));
    thrown.expectMessage(
        "Batch update returned unexpected row count from update");
    thrown.expectCause(isA(StaleStateException.class));

    Session session = null;
    Transaction transaction = null;

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        Product product = new Product();
        product.setId(12);
        product.setName("Product 12");
        session.save(product1);
        transaction.commit();
        session.close();

        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        product = session.get(Product.class, 12);
        session.createNativeQuery("delete from Product where id=12")
          .executeUpdate();
        // We need to refresh to fix the error.
        // session.refresh(product);
        session.delete(product);
        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
    }
}

Likewise, we can also get this error if two users try to update the same entity at almost the same time. In this case, the first may succeed and the second raises this error.

Therefore, we cannot completely avoid this error without introducing pessimistic locking. However, we can minimize the probability of its occurrence by doing the following:

  • Keep update operations as short as possible.
  • Update entity representations in the client as often as possible.
  • Do not cache the entity or any value object representing it.
  • Always refresh the entity representation on the client after an update.

10. Conclusion

In this article, we looked into some common exceptions encountered while using Hibernate. Furthermore, we investigated their probable causes and resolutions.

As usual, the full source code can be found over on GitHub.