Home » Enterprise Java » hibernate » Hibernate Exception Handling Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Hibernate Exception Handling Example

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 read this 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

An exception 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 the EntityManager.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 throws SQLException. Hibernate provides better handle than the JDBCException.

Developers can use the try and catch 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 are FATAL, hence developers have to roll-back the transaction and close the current session object immediately.

2.1 Common Hibernate Exceptions and How to Fix Them

2.1.1 LazyInitializationException

Hibernate throws a LazyInitializationException 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 a LazyInitializationException 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 the OptimisticLockException. 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 1
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
		
// EntityManager and Transaction 2
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

// Update 1
Author a = em.find(Author.class, 1L);
a.setFirstName("changed");
		
// Update 2
Author a2 = em2.find(Author.class, 1L);
a2.setFirstName("changed");

// Commit Transaction 1
em.getTransaction().commit();
em.close();
		
// Commit Transaction 2
try {
	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 a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

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 ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of