hibernate

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

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button