Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Hibernate Interceptor Example

In this example we are going to see how to use Hibernate Interceptor. During a Hinernate transaction, an object might go through a number of phases: it is created, it gets updated, it gets persisted or deleted. An Interceptor detects the most basic events in the database, like CRUD operations. On each events it fires up callback methods. There are numerus usages of this feature, and as you can imagine one of the most basic is logging.

You can use an Interceptor to log a list of events that happend during. The thing is that you can use any logging methods or frameworks you want, so that makes your program easily extendible. Or you can even log your events in a database table without using any logging framworks or the client machine’s file system, which make it more portable.

o these are the tools we are going to use on a Windows 7 platform:

  • JDK 1.7
  • Maven 3.0.5
  • Hibernate 4.2.3.Final
  • MySQL JDBC driver 5.1.9
  • Eclipse 4.3 Kepler

The basis of this tutorials is going to be this Eclipse project: HibernateMySQLExample.zip. And it’s based in Hibernate 3 with Maven 2 and MySQL 5 Example (XML Mapping and Annotation).

1. Create an EmptyInterceptor class

Remember that the structure of the the project we are going to use is this:

project-structure

In order to use an Interceptor with our Session, we need to create a class that extends EmptyInterceptor.. Go to the com.javacodegeeks.enterprise.hibernate package on the Package Explorer and create a new class with name MyInterceptor. And now paste the following code:

MyInterceptor.java:

package com.javacodegeeks.enterprise.hibernate;

import java.io.Serializable;
import java.util.Iterator;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class MyInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 1L;

   public void onDelete(Object entity,
                     Serializable id,
                     Object[] state,
                     String[] propertyNames,
                     Type[] types) {

       // log delete events
	   System.out.println("Delete event");
   }

   // called when a Student gets updated.
   public boolean onFlushDirty(Object entity,
                     Serializable id,
                     Object[] currentState,
                     Object[] previousState,
                     String[] propertyNames,
                     Type[] types) {
       if ( entity instanceof Student ) {
          System.out.println("Student Update Operation");
          return true; 
       }
       return false;
   }

   // called on load events
   public boolean onLoad(Object entity,
                    Serializable id,
                    Object[] state,
                    String[] propertyNames,
                    Type[] types) {

       // log loading events
	   System.out.println("Load Operation");
       return true;
   }

   public boolean onSave(Object entity,
                    Serializable id,
                    Object[] state,
                    String[] propertyNames,
                    Type[] types) {
       if ( entity instanceof Student ) {
          System.out.println("Student Create Operation");
          return true; 
       }
       return false;
   }

   //called before commit into database
   public void preFlush(Iterator iterator) {
      System.out.println("Before commiting");
   }

   //called after committed into database
   public void postFlush(Iterator iterator) {
      System.out.println("After commiting");
   }
}

These are the most basic methods that an Interceptor implements:

  • onSave : Called when you save an object. The object is not persisted yet.
  • onFlushDirty : Called when you update an object. The object is not persisted yet.
  • onDelete : Called when you delete an object. The object is not deleted from the database yet.
  • preFlush : Called before committing to the database.
  • postFlush :  Called after committing to the database.

We should also update HibernateUtil class:

HibernateUtil.java:

package com.javacodegeeks.enterprise.hibernate.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.javacodegeeks.enterprise.hibernate.MyInterceptor;

public class HibernateUtil {

	private static SessionFactory sessionFactory = buildSessionFactory();
	private static ServiceRegistry serviceRegistry;

	private static SessionFactory buildSessionFactory() {

		   Configuration configuration = new Configuration().setInterceptor(new MyInterceptor());
	        configuration.configure();
	        serviceRegistry = new ServiceRegistryBuilder().
applySettings(configuration.getProperties()).buildServiceRegistry();        
	        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	        return sessionFactory;		
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		getSessionFactory().close();
	}

}

Now update the App.java file to test the Interceptor.

App.java:

package com.javacodegeeks.enterprise.hibernate;

import org.hibernate.Query;
import org.hibernate.Session;

import com.javacodegeeks.enterprise.hibernate.utils.HibernateUtil;

public class App 
{
    public static void main( String[] args ) {

        Session session = HibernateUtil.getSessionFactory().openSession();

       //test insert
        System.out.println("*** Test insert ***");

        session.beginTransaction();
        Student student = new Student();

        student.setStudentName("JavaFun");
        student.setStudentAge("19");

        session.saveOrUpdate(student);
        session.getTransaction().commit();

      //test update
        System.out.println("*** Test Update ***");

        session.beginTransaction();
        Query query = session.createQuery("from Student where studentId = 59");
        Student studentToUpdate = (Student)query.list().get(0);
        studentToUpdate.setStudentName("Lakis");
    	session.saveOrUpdate(studentToUpdate);
        session.getTransaction().commit();

      //test delete
        System.out.println("*** Test Delete ***");
        session.beginTransaction();
        session.delete(studentToUpdate);
        session.getTransaction().commit();

    }
}

Output:

*** Test insert ***
Student Create Operation
Hibernate: insert into tutorials.student (STUDENT_NAME, STUDENT_Age) values (?, ?)
Before commiting
After commiting
*** Test Update ***
Before commiting
Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.STUDENT_NAME as STUDENT2_0_, student0_.STUDENT_Age as STUDENT3_0_ from tutorials.student student0_ where student0_.STUDENT_ID=58
Load Operation
Before commiting
Student Update Operation
Hibernate: update tutorials.student set STUDENT_NAME=?, STUDENT_Age=? where STUDENT_ID=?
After commiting
*** Test Delete ***
Delete event
Before commiting
Hibernate: delete from tutorials.student where STUDENT_ID=?
After commiting

This was an example on Hibernate Interceptor.

Download the Eclipse project of this tutorial : HibernateInterceptor.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close