Exceptions courantes de mise en veille prolongée

1. Introduction

Dans ce didacticiel, nous discuterons de certaines exceptions courantes que nous pouvons rencontrer en travaillant avec Hibernate.

Nous passerons en revue leur objectif et certaines causes courantes. De plus, nous examinerons leurs solutions.

2. Présentation des exceptions Hibernate

De nombreuses conditions peuvent entraîner la levée d'exceptions lors de l'utilisation d'Hibernate. Il peut s'agir d'erreurs de mappage, de problèmes d'infrastructure, d'erreurs SQL, de violations d'intégrité des données, de problèmes de session et d'erreurs de transaction.

Ces exceptions s'étendent principalement de HibernateException . Cependant, si nous utilisons Hibernate comme fournisseur de persistance JPA, ces exceptions peuvent être encapsulées dans PersistenceException .

Ces deux classes de base s'étendent de RuntimeException . Par conséquent, ils ne sont tous contrôlés. Par conséquent, nous n'avons pas besoin de les attraper ou de les déclarer à chaque endroit où ils sont utilisés.

De plus , la plupart d'entre eux sont irrécupérables. Par conséquent, réessayer l'opération n'aiderait pas. Cela signifie que nous devons abandonner la session en cours en les rencontrant.

Examinons maintenant chacun de ces éléments, un à la fois.

3. Erreurs de mappage

Le mappage objet-relationnel est un avantage majeur d'Hibernate. Plus précisément, cela nous libère de l'écriture manuelle d'instructions SQL.

En même temps, cela nous oblige à spécifier le mappage entre les objets Java et les tables de base de données. En conséquence, nous les spécifions à l'aide d'annotations ou de documents cartographiques. Ces mappages peuvent être codés manuellement. Alternativement, nous pouvons utiliser des outils pour les générer.

En spécifiant ces mappages, nous pouvons faire des erreurs. Ceux-ci pourraient être dans la spécification de mappage. Ou, il peut y avoir une incompatibilité entre un objet Java et la table de base de données correspondante.

De telles erreurs de mappage génèrent des exceptions. Nous les rencontrons fréquemment lors du développement initial. De plus, nous pouvons les rencontrer lors de la migration des changements entre les environnements.

Examinons ces erreurs avec quelques exemples.

3.1. MappingException

Provoque un Un problème avec le mapping objet-relationnel MappingException à être jeté :

public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { thrown.expectCause(isA(MappingException.class)); thrown.expectMessage("Unknown entity: java.lang.String"); Session session = sessionFactory.getCurrentSession(); NativeQuery query = session .createNativeQuery("select name from PRODUCT", String.class); query.getResultList(); }

Dans le code ci-dessus, la méthode createNativeQuery essaie de mapper le résultat de la requête sur le type Java spécifié String. Il utilise le mappage implicite de la classe String de Metamodel pour effectuer le mappage.

Cependant, la classe String n'a aucun mappage spécifié. Par conséquent, Hibernate ne sait pas comment mapper la colonne de nom à String et lève l'exception.

Pour une analyse détaillée des causes et des solutions possibles, consultez Exception de mappage Hibernate - Entité inconnue.

De même, d'autres erreurs peuvent également provoquer cette exception:

  • Mélanger les annotations sur les champs et les méthodes
  • Ne pas spécifier la @JoinTable pour une association @ManyToMany
  • Le constructeur par défaut de la classe mappée lève une exception lors du traitement du mappage

De plus, MappingException a quelques sous-classes qui peuvent indiquer des problèmes de mappage spécifiques:

  • AnnotationException - un problème avec une annotation
  • DuplicateMappingException - mappage en double pour un nom de classe, de table ou de propriété
  • InvalidMappingException - le mappage n'est pas valide
  • MappingNotFoundException - la ressource de mappage est introuvable
  • PropertyNotFoundException - une méthode getter ou setter attendue est introuvable sur une classe

Par conséquent, si nous rencontrons cette exception, nous devons d'abord vérifier nos mappages .

3.2. AnnotationException

Pour comprendre AnnotationException, créons une entité sans annotation d'identifiant sur un champ ou une propriété:

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

Étant donné qu'Hibernate s'attend à ce que chaque entité ait un identifiant , nous obtiendrons une AnnotationException lorsque nous utiliserons l'entité:

public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { thrown.expect(AnnotationException.class); thrown.expectMessage("No identifier specified for entity"); Configuration cfg = getConfiguration(); cfg.addAnnotatedClass(EntityWithNoId.class); cfg.buildSessionFactory(); }

En outre, certaines autres causes probables sont:

  • Générateur de séquence inconnu utilisé dans l' annotation @GeneratedValue
  • @ Annotation temporelle utilisée avec une classe Date / Heure Java 8
  • Entité cible manquante ou inexistante pour @ManyToOne ou @OneToMany
  • Classes de collection brutes utilisées avec les annotations de relation @OneToMany ou @ManyToMany
  • Classes concrètes utilisées avec les annotations de collection @OneToMany , @ManyToMany ou @ElementCollection car Hibernate attend les interfaces de collection

Pour résoudre cette exception, nous devons d'abord vérifier l'annotation spécifique mentionnée dans le message d'erreur.

4. Erreurs de gestion de schéma

La gestion automatique des schémas de base de données est un autre avantage d'Hibernate. Par exemple, il peut générer des instructions DDL pour créer ou valider des objets de base de données.

Pour utiliser cette fonctionnalité, nous devons définir la propriété hibernate.hbm2ddl.auto de manière appropriée.

S'il y a des problèmes lors de l'exécution de la gestion du schéma, nous obtenons une exception. Examinons ces erreurs.

4.1. SchemaManagementException

Tout problème lié à l'infrastructure lors de l'exécution de la gestion des schémas provoque une exception SchemaManagementException .

Pour démontrer, demandons à Hibernate de valider le schéma de base de données:

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(); }

La table correspondant à Product n'étant pas présente dans la base de données, nous obtenons l'exception de validation de schéma lors de la construction de la S essionFactory .

En outre, il existe d'autres scénarios possibles pour cette exception:

  • impossible de se connecter à la base de données pour effectuer des tâches de gestion de schéma
  • 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:

public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); thrown.expectMessage("SQLGrammarException: could not prepare statement"); Session session = sessionFactory.getCurrentSession(); NativeQuery 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.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); thrown .expectMessage("SQLGrammarException: 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.expect(isA(PersistenceException.class)); thrown.expectCause(isA(ConstraintViolationException.class)); thrown.expectMessage( "ConstraintViolationException: 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( "org.hibernate.exception.DataException: could not prepare statement"); Session session = sessionFactory.getCurrentSession(); NativeQuery query = session.createNativeQuery( "select * from PRODUCT where", 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. 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.6. 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

6. Session-State-Related Errors

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:

public void whenUpdatingNonExistingObject_thenStaleStateException() { 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(15); product.setName("Product1"); session.update(product); 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 in order 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 in order 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 IllegalArgumentException depending on the transaction manager.

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

public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { thrown.expect(isA(TransactionException.class)); thrown.expectMessage( "Transaction was marked for rollback only; cannot commit"); Session session = null; Transaction transaction = null; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); Product product = new Product(); product.setId(15); product.setName("Product1"); session.save(product); 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); } }

De même, nous pouvons également obtenir cette erreur si deux utilisateurs essaient de mettre à jour la même entité presque en même temps. Dans ce cas, le premier peut réussir et le second déclenche cette erreur.

Par conséquent, nous ne pouvons pas complètement éviter cette erreur sans introduire un verrouillage pessimiste . Cependant, nous pouvons minimiser la probabilité de son apparition en procédant comme suit:

  • Gardez les opérations de mise à jour aussi courtes que possible
  • Mettre à jour les représentations d'entités dans le client aussi souvent que possible
  • Ne mettez pas en cache l'entité ou tout objet de valeur la représentant
  • Actualisez toujours la représentation d'entité sur le client après la mise à jour

10. Conclusion

Dans cet article, nous avons examiné certaines exceptions courantes rencontrées lors de l'utilisation d'Hibernate. De plus, nous avons étudié leurs causes probables et leurs résolutions.

Comme d'habitude, le code source complet peut être trouvé sur GitHub.