hibernate

Hibernate Exception Handling Example

Photo of YatinYatinAugust 28th, 2017Last Updated: February 20th, 2019
1 1,705 4 minutes read

This tutorial deals with some of the errors that developers get, while working with Hibernate. Along with the exception or error messages themselves, potential causes of these errors are often listed along with links to additional resources. In this tutorial, we will discuss the Hibernate exceptions.
 
 
 
 
 
 
 

1. Introduction

1.1 Hibernate

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling
  • The Framework provides the option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration
  • The Framework handles the application interaction with the database, leaving the developer free to concentrate more on business logic and solving complex problems

Fig. 1: Hibernate Overview
Fig. 1: Hibernate Overview

1.1.1 Hibernate Benefits

Hibernate is an ORM implementation. Like many other implementations, it has a numerous number of pros and cons:

  • Database Independent: Hibernate is independent of the database engine at the backend. The list of the Hibernate Dialect is provided for connecting whatever database we prefer
  • JPA Provider: Java Persistence API (JPA) is a specification. Hibernate is a standard ORM solution and it has a JPA capability. Hence, the use of hibernate would help you leverage all the capabilities of ORM and the JPA in a JPA-specific project
  • Built-In Connection Pool: Hibernate has been integrated automatically with the most reliable connection pool implementation i.e. C3P0
  • Layered Architecture: Hibernate is a layered architecture, so developers don’t have to be obligated to use everything provided by the framework

1.2 Download and Install Hibernate

You can readthis tutorial in order to download and install Hibernate in the Eclipse IDE.

Now, let’s take a look and understand the exception handling in Hibernate framework!

2. Hibernate Exception Handling

Anexception is kind of error generated during the execution of a program. It interrupts the normal flow of the program and there are many reasons of exceptions, like:

  • Entered invalid data
  • A File that you want to fetch is not found
  • Some network problem or Out of Memory run

Entity Manager handle exceptions as by calling theEntityManager.close() method which discard the changes and rollback the database transaction. In general,EntityManager handle Hibernate core exception. Some of them are:

  • IllegalArgumentException: Wrong argument or fail to recognized, or having the incorrect format etc.
  • EntityNotFoundException: An Entity was expected but did not match the requirement
  • TransactionRequiredException: This operation has to be in a Transaction object
  • IllegalStateException: Wrong way of using the Entity Manager

Hibernate works with most of unchecked Hibernate persistence layer exceptions. When Hibernate interacts with the database it throwsSQLException. Hibernate provides better handle than theJDBCException.

Developers can use thetry andcatch block to handle the exceptions. Put the line of code that may cause an exception in a try block and according to that exception put the exception handler in the catch block. Here is an example. We are putting the code of updating in the try block which will be handled by Hibernate Exception in catch block.

Example.java

package com.hibernate.exception.handling;import com.hibernate.exception.handling.model.Student;import com.hibernate.exception.handling.util.HibernateUtil;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;public class HibernateUpdate {public static void main(String args[]) {Session sessionObj = HibernateUtil.getSessionFactory().openSession();int roll = 5;Transaction transactionObj = sessionObj.beginTransaction();Student studentObj = (Student) session.load(Student.class, roll);try {studentObj.setName("Java Code Geek");studentObj.setCourse("Hibernate");sessionObj.merge(studentObj);transactionObj.commit();System.out.println("Update Successfully");sessionObj.close();} catch (HibernateException hibernateEx) {try {transactionObj.rollback();} catch(RuntimeException runtimeEx){System.err.printf("Couldn’t Roll Back Transaction", runtimeEx);}hibernateEx.printStackTrace();} finally {if(sessionObj!= null) {sessionObj.close();}}}}

Note: Any exceptions thrown by the Hibernate framework areFATAL, hence developers have to roll-back the transaction and close the current session object immediately.

Want to be a Hibernate Master ?
Subscribe to our newsletter and download the HibernateUltimateGuideright now!
In order to help you master JPA and database programming with Hibernate, we have compiled a kick-ass guide with all the major Hibernate features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

2.1 Common Hibernate Exceptions and How to Fix Them

2.1.1 LazyInitializationException

Hibernate throws aLazyInitializationException if you try to access a not initialized relationship to another entity without an active session. You can see a simple example for this in the following code snippet.

Example.java

EntityManager em = emf.createEntityManager();em.getTransaction().begin();Author a = em.find(Author.class, 1L);em.getTransaction().commit();em.close();logger.info(a.getFirstName() + " " + a.getLastName() + " wrote "+a.getBooks().size() + " books.");

The best way to fix aLazyInitializationException is to initialize the required relationship in the business tier. But don’t initialize all relationships just because there might be one client out there who needs one of them. For performance reasons, you should only initialize the relationships you need.

2.1.2 OptimisticLockException

Another very common exception is theOptimisticLockException. Hibernate throws it when you use optimistic locking and detects a conflicting update of an entity. That most often happens for one of two reasons:

  • 2 users try to update the same entity at nearly the same point in time
  • 1 user performs 2 updates of the same entity, and developers didn’t refresh the entity representation in the client so that the version value wasn’t updated after the first update

Developers can see a test case with 2 concurrent updates in the following code snippet.

Example.java

// EntityManager and Transaction 1EntityManager em = emf.createEntityManager();em.getTransaction().begin();// EntityManager and Transaction 2EntityManager em2 = emf.createEntityManager();em2.getTransaction().begin();// Update 1Author a = em.find(Author.class, 1L);a.setFirstName("changed");// Update 2Author a2 = em2.find(Author.class, 1L);a2.setFirstName("changed");// Commit Transaction 1em.getTransaction().commit();em.close();// Commit Transaction 2try {em2.getTransaction().commit();Assert.fail();} catch (RollbackException e) {log.info("2nd transaction failed with an OptimisticLockException");}em2.close();

This works fine until I try to commit the second transaction and Hibernate checks for concurrent updates of this Author entity. In a real world application, this would, of course, be done by 2 parallel calls of the same method.

That’s all for this post. Happy Learning!!

6. Conclusion

These were my most common Hibernate Exceptions. I suggested some solutions that help me and developers can do the same to handle similar situations. As you have seen, Exceptions and the reason that happen are different things. Some of them only occur during the development and others will hit directly in the production. So better watch out and make sure that you’re familiar with these kind of problems. That’s all for this tutorial and I hope this article served you whatever you were looking for.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinAugust 28th, 2017Last Updated: February 20th, 2019
1 1,705 4 minutes read
Photo of Yatin

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.