Hibernate Interceptors

Posted: June 19, 2012 in Hibernate

We know about interceptors are available in frameworks like strus2, spring. Even Hibernate ORM tool also having this kind of feature. Interceptor means request processing life cycle. Interceptors will be invoked based on the requirement like before saving a record into table, updating record, deleting a record and so..on.

In Hibernate I have gone through the EmptyInterceptor  class. It doesn’t have any methods we ourselves configure the methods like below.

1 findDirty()
This method is be called when the flush() method is called on a Session object.
2 instantiate()
This method is called when a persisted class is instantiated.
3 isUnsaved()
This method is called when an object is passed to the saveOrUpdate() method/
4 onDelete()
This method is called before an object is deleted.
5 onFlushDirty()
This method is called when Hibernate detects that an object is dirty (ie. have been changed) during a flush i.e. update operation.
6 onLoad()
This method is called before an object is initialized.
7 onSave()
This method is called before an object is saved.
8 postFlush()
This method is called after a flush has occurred and an object has been updated in memory.
9 preFlush()
This method is called before a flush.

Let see our application developed using hibernateinterceptor concept and following files are needed.

  1. Usermaster (table)
  2. Usermaster.java
  3. Usermaster.hbm.xml
  4. Hibernate.cfg.xml
  5. HibernateUtil.java (for singleton ——> session)
  6. MyInterceptro.java (extends EmptyInterceptor available in Hibernate)
  7. FirstExample.java (main method class)

1)      Usermaster table

create table usermaster(

`sno` int(3) NOT NULL AUTO_INCREMENT,

`username` varchar(15) DEFAULT NULL,

`password` varchar(15) DEFAULT NULL,

`status` int(1) DEFAULT NULL,

PRIMARY KEY (`sno`)

)

2)      Usermaster.java (pojo class)

public class Usermaster {

private int sno;

private String username;

private String password;

private int status;

public int getSno() {

return sno;

}

public void setSno(int sno) {

this.sno = sno;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getStatus() {

return status;

}

public void setStatus(int status) {

this.status = status;

}

}

3)      Usermaster.hbm.xml

<?xml version=”1.0″?>

<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”

http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;

<!– Generated Mar 2, 2011 6:39:02 PM by Hibernate Tools 3.4.0.CR1 –>

<hibernate-mapping>

<class name=”com.shal.model.Usermaster” table=”usermaster”>

<id name=”sno” type=”java.lang.Integer”>

<column name=”sno” />

<generator />

</id>

<property name=”username” type=”string”>

<column name=”username” length=”30″ />

</property>

<property name=”password” type=”string”>

<column name=”password” length=”30″ />

</property>

<property name=”status” type=”java.lang.Integer”>

<column name=”status” length=”20″ />

</property>

</class>

</hibernate-mapping>

4)      Hibernate.cfg.xml

<?xml version=’1.0′ encoding=’utf-8′?>

<!DOCTYPE hibernate-configuration PUBLIC

“-//Hibernate/Hibernate Configuration DTD//EN”

http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;

<hibernate-configuration>

<session-factory>

<property name=”connection.useUnicode”>true</property>

<property name=”connection.characterEncoding”>UTF-8</property>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”connection.url”>jdbc:mysql://localhost/test</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>gopal</property>

<property name=”show_sql”>true</property>

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=”current_session_context_class”>thread</property>

<property name=”hibernate.transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory</property>

<mapping resource=”com/shal/model/Usermaster.hbm.xml”/>

</session-factory>

</hibernate-configuration>

5)      HibernateUtil.java

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()

{                                try {

// Create the SessionFactory from hibernate.cfg.xml

return new AnnotationConfiguration().configure().buildSessionFactory();

} catch (Throwable ex) {

System.err.println(“Initial SessionFactory creation failed.” + ex);

throw new ExceptionInInitializerError(ex);

}

}

public static SessionFactory getSessionFactory() {

return sessionFactory;

}

}

6)      MyInterceptor.java

public class MyInterceptor extends EmptyInterceptor {

private int updates;

private int creates;

private int loads;

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

System.out.println(“Delete Operation”);

}

// This method is called when Employee object gets updated.

public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState,Object[] previousState,String[] propertyNames,

Type[] types) {

if ( entity instanceof Object ) {

System.out.println(“Update Operation”);

return true;

}

return false;

}

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

// do nothing

return true;

}

// This method is called when Employee object gets created.

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

if ( entity instanceof Object ) {

System.out.println(“Create Operation”);

return true;

}

return false;

}

//called before commit into database

public void preFlush(Iterator iterator) {

System.out.println(“preFlush”);

}

//called after committed into database

public void postFlush(Iterator iterator) {

System.out.println(“postFlush”);

}

}

7)      FirstExample.java

public class FirstExample{

public static void main(String args[])

{

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

session.beginTransaction().begin();

//Before Saving

Usermaster usermaster = new Usermaster();

try

{

usermaster.setUsername(“Gopal”);

usermaster.setPassword(“gopal123”);

usermaster.setStatus(new Integer(1));

session.save(usermaster);

session.beginTransaction().commit();

}catch(Exception e)

{

session.beginTransaction().rollback();

e.printStackTrace();

}

//Updating the record

try

{

Usermaster usermaster1 = (Usermaster)session.get(Usermaster.class,new Integer(1));

usermaster1.setPassword(“123gopal”);

session.update(usermaster1);

session.beginTransaction().commit();

}catch(Exception e)

{

session.beginTransaction().rollback();

e.printStackTrace();

}

//Deleting the Record

try

{

Usermaster usermaster2 = (Usermaster)session.get(Usermaster.class,new Integer(1));

session.delete(usermaster2);

session.beginTransaction().commit();

}catch(Exception e)

{

session.beginTransaction().rollback();

e.printStackTrace();

}

}

}

Output:

Create Operation

preFlush

postFlush

Update Operation

preFlush

postFlush

Delete Operation

preFlush

postFlush

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s