In order to use an
We should also update
Interceptor
with our Session
, we need to create a class that extends EmptyInterceptor.
. Create a new class with name DataInterceptor.java
. And now paste the following code:
package com.pkm.commands; import java.io.Serializable; import java.util.Iterator; import org.hibernate.EmptyInterceptor; import org.hibernate.Transaction; public class DataInterceptor extends EmptyInterceptor { private int updates = 0; private int creates = 0; private int loads = 0; private int deletes = 0; @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, org.hibernate.type.Type[] types) { System.out.println("onSave"); creates++; return true; } // called on load events @Override public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, org.hibernate.type.Type[] types) { System.out.println("onLoad"); loads++; return true; } @Override public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, org.hibernate.type.Type[] types) { System.out.println("onFlushDirty"); updates++; return false; } @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, org.hibernate.type.Type[] types) { System.out.println("onDelete"); deletes++; } //called before commit into database @Override public void preFlush(Iterator iterator) { System.out.println("preFlush"); } //called after committed into database @Override public void postFlush(Iterator iterator) { System.out.println("postFlush"); } @Override public void afterTransactionCompletion(Transaction tx) { if ( tx.wasCommitted() ) { System.out.println("Creations: " + creates + ", Updates: " + updates + ", Loads: " + loads + ", Deletes: " + deletes); } } }
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.
- onLoad: Called when you read an object from database.
- 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:
package com.pkm.utils; import com.pkm.commands.DataInterceptor; import org.hibernate.service.ServiceRegistry; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static ServiceRegistry serviceRegistry; private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration().setInterceptor(new DataInterceptor()); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); return configuration.buildSessionFactory(serviceRegistry); } catch (Exception ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
Now create main java class file to test the Interceptor.
package com.pkm.commands; import com.pkm.domains.User; import com.pkm.utils.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class TestInterceptor { @SuppressWarnings("unchecked") public static void main(String[] args) { Session session = null; Transaction transaction = null; try { session = HibernateUtil.getSessionFactory().openSession(); transaction = session.beginTransaction(); User user = new User(System.currentTimeMillis() + "@gmail.com", "Pritom", "Kumar Mondal"); session.save(user); Long firstId = user.getId(); user = new User(System.currentTimeMillis() + "@gmail.com", "Pritom", "Kumar Mondal"); session.save(user); Long secondId = user.getId(); user = (User) session.get(User.class, firstId); user.setFirstName("First name changed"); session.save(user); user = (User) session.get(User.class, secondId); session.delete(user); user = (User) session.get(User.class, Long.parseLong("10")); user = (User) session.get(User.class, Long.parseLong("11")); user = (User) session.get(User.class, Long.parseLong("12")); transaction.commit(); } catch (Exception ex) { if(transaction != null) { transaction.rollback(); } System.err.println(ex.getMessage()); } finally { if(session != null) { session.close(); } } } }
Output of Example:
onSave Hibernate: insert into User (email, first_name, last_name) values (?, ?, ?) onSave Hibernate: insert into User (email, first_name, last_name) values (?, ?, ?) onDelete Hibernate: select user0_.id as id0_0_, user0_.email as email0_0_, user0_.first_name as first3_0_0_, user0_.last_name as last4_0_0_ from User user0_ where user0_.id=? onLoad Hibernate: select user0_.id as id0_0_, user0_.email as email0_0_, user0_.first_name as first3_0_0_, user0_.last_name as last4_0_0_ from User user0_ where user0_.id=? onLoad Hibernate: select user0_.id as id0_0_, user0_.email as email0_0_, user0_.first_name as first3_0_0_, user0_.last_name as last4_0_0_ from User user0_ where user0_.id=? onLoad preFlush onFlushDirty Hibernate: update User set email=?, first_name=?, last_name=? where id=? Hibernate: delete from User where id=? postFlush Creations: 2, Updates: 1, Loads: 3, Deletes: 1