Pengecualian Hibernasi Umum

1. Perkenalan

Dalam tutorial ini, kita akan membahas beberapa pengecualian umum yang dapat kita temui saat bekerja dengan Hibernate.

Kami akan meninjau tujuan mereka dan beberapa penyebab umum. Selain itu, kami akan melihat solusinya.

2. Ikhtisar Pengecualian Hibernasi

Banyak kondisi yang dapat menyebabkan pengecualian untuk dilemparkan saat menggunakan Hibernate. Ini bisa berupa kesalahan pemetaan, masalah infrastruktur, kesalahan SQL, pelanggaran integritas data, masalah sesi, dan kesalahan transaksi.

Pengecualian ini sebagian besar berasal dari HibernateException . Namun, jika kami menggunakan Hibernate sebagai penyedia persistensi JPA, pengecualian ini dapat dimasukkan ke dalam PersistenceException .

Kedua kelas dasar ini diturunkan dari RuntimeException . Oleh karena itu, semuanya tidak dicentang. Karenanya, kita tidak perlu menangkap atau mendeklarasikannya di setiap tempat mereka digunakan.

Selain itu, sebagian besar tidak dapat dipulihkan. Akibatnya, mencoba kembali operasi tidak akan membantu. Ini berarti kita harus meninggalkan sesi saat ini saat bertemu dengan mereka.

Sekarang mari kita lihat masing-masing ini, satu per satu.

3. Kesalahan Pemetaan

Pemetaan Objek-Relasional adalah manfaat utama Hibernate. Secara khusus, ini membebaskan kita dari penulisan pernyataan SQL secara manual.

Pada saat yang sama, ini mengharuskan kita untuk menentukan pemetaan antara objek Java dan tabel database. Karenanya, kami menetapkannya menggunakan anotasi atau melalui dokumen pemetaan. Pemetaan ini dapat dikodekan secara manual. Alternatifnya, kita dapat menggunakan alat untuk membuatnya.

Saat menentukan pemetaan ini, kami mungkin membuat kesalahan. Ini bisa jadi dalam spesifikasi pemetaan. Atau, mungkin ada ketidakcocokan antara objek Java dan tabel database terkait.

Kesalahan pemetaan seperti itu menghasilkan pengecualian. Kami sering menjumpai mereka selama pengembangan awal. Selain itu, kami mungkin menemukannya saat memigrasi perubahan lintas lingkungan.

Mari kita lihat kesalahan ini dengan beberapa contoh.

3.1. MappingException

Masalah dengan pemetaan relasional objek menyebabkan MappingException dilemparkan :

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

Dalam kode di atas, metode createNativeQuery mencoba memetakan hasil kueri ke String tipe Java yang ditentukan . Ia menggunakan pemetaan implisit kelas String dari Metamodel untuk melakukan pemetaan.

Namun, kelas String tidak menetapkan pemetaan apa pun. Oleh karena itu, Hibernate tidak tahu bagaimana memetakan kolom nama ke String dan membuang pengecualian.

Untuk analisis rinci tentang kemungkinan penyebab dan solusi, lihat Pengecualian Pemetaan Hibernasi - Entitas Tidak Dikenal.

Demikian pula, kesalahan lain juga dapat menyebabkan pengecualian ini:

  • Mencampur anotasi pada bidang dan metode
  • Gagal menentukan @JoinTable untuk asosiasi @ManyToMany
  • Konstruktor default dari kelas yang dipetakan melontarkan pengecualian selama pemrosesan pemetaan

Selain itu, MappingException memiliki beberapa subclass yang dapat menunjukkan masalah pemetaan tertentu:

  • AnnotationException - masalah dengan anotasi
  • DuplicateMappingException - pemetaan duplikat untuk kelas, tabel, atau nama properti
  • InvalidMappingException - pemetaan tidak valid
  • MappingNotFoundException - resource pemetaan tidak dapat ditemukan
  • PropertyNotFoundException - metode pengambil atau penyetel yang diharapkan tidak dapat ditemukan di kelas

Oleh karena itu, jika kami menemukan pengecualian ini, pertama-tama kami harus memverifikasi pemetaan kami .

3.2. AnnotationException

Untuk memahami AnnotationException, mari buat entitas tanpa anotasi pengenal di bidang atau properti apa pun:

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

Karena Hibernate mengharapkan setiap entitas memiliki pengenal , kita akan mendapatkan AnnotationException saat kita menggunakan entitas:

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

Selain itu, beberapa kemungkinan penyebab lainnya adalah:

  • Generator urutan tidak dikenal digunakan dalam anotasi @GeneratedValue
  • @ Anotasi waktu digunakan dengan kelas Tanggal / Waktu Java 8
  • 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.

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:

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

Demikian juga, kami juga bisa mendapatkan kesalahan ini jika dua pengguna mencoba memperbarui entitas yang sama di waktu yang hampir bersamaan. Dalam kasus ini, yang pertama mungkin berhasil dan yang kedua memunculkan kesalahan ini.

Oleh karena itu, kami tidak dapat sepenuhnya menghindari kesalahan ini tanpa melakukan penguncian pesimis . Namun, kami dapat meminimalkan kemungkinan kemunculannya dengan melakukan hal berikut:

  • Pertahankan operasi pembaruan sesingkat mungkin
  • Perbarui representasi entitas di klien sesering mungkin
  • Jangan meng-cache entitas atau objek nilai apa pun yang mewakilinya
  • Selalu segarkan representasi entitas pada klien setelah pembaruan

10. Kesimpulan

Pada artikel ini, kami melihat beberapa pengecualian umum yang ditemui saat menggunakan Hibernate. Selain itu, kami menyelidiki kemungkinan penyebab dan resolusi mereka.

Seperti biasa, kode sumber lengkap dapat ditemukan di GitHub.