Hibernate SessionEventListener and Session.addEventListeners() Example
February 12, 2015
In this page we will learn Hibernate SessionEventListener and Session.addEventListeners(). There are many events in the life cycle of a Hibernate Session that can be listened. To achieve this task Hibernate 4 provides org.hibernate.SessionEventListener which has different methods as below
flushStart()
flushEnd()
dirtyCalculationStart()
dirtyCalculationEnd()
end()
And so many other methods. There are some implementations of this interface in Hibernate as
org.hibernate.engine.internal.SessionEventListenerManagerImpl and
org.hibernate.engine.internal.StatisticalLoggingSessionEventListener
Now we can extend these classes or directly interface to implement our own Session Event listener. And finally add this listener to session using org.hibernate.Session.addEventListeners()
Create your own SessionEventListener
Hibernate provides org.hibernate.engine.internal.SessionEventListenerManagerImpl which implements SessionEventListener. Now using SessionEventListenerManagerImpl, we can create our own class that will override required methods. For the example we are using some methods as below.MySessionEventListener.java
package com.concretepage; import org.hibernate.engine.internal.SessionEventListenerManagerImpl; public class MySessionEventListener extends SessionEventListenerManagerImpl { private static final long serialVersionUID = 1L; @Override public void flushStart() { System.out.println("--flushStart--"); } @Override public void flushEnd(int numberOfEntities, int numberOfCollections) { System.out.println("--flushEnd--numberOfEntities:"+numberOfEntities); } @Override public void dirtyCalculationStart() { System.out.println("--dirtyCalculationStart--"); } @Override public void dirtyCalculationEnd(boolean dirty) { System.out.println("--dirtyCalculationEnd--isDirty:"+dirty); } @Override public void end() { System.out.println("End"); } }
Use Session.addEventListeners()
To add our listener, hibernate provides a method in Session as given belowSession.addEventListeners(SessionEventListener... listeners) : We can pass all our listener using this method as it accepts arguments as Varargs.
Find the sample code how to use it.
SessionEventListenerDemo.java
package com.concretepage; import org.hibernate.Session; import org.hibernate.SessionEventListener; public class SessionEventListenerDemo { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Student s = new Student(1, 23, "Rahim"); SessionEventListener listener = new MySessionEventListener(); session.addEventListeners(listener); session.save(s); session.getTransaction().commit(); session.close(); } }
--flushStart-- --dirtyCalculationStart-- --dirtyCalculationEnd--isDirty:false Hibernate: insert into student (age, name, id) values (?, ?, ?) --flushEnd--numberOfEntities:1 End