I created a simple hello-wordish code using hibernate
sf = new Configuration().configure().buildSessionFactory();
System.out.println("sessionFactory is built.Get session object");
s = sf.openSession();
Kk emp = (Kk) s.get(Kk.class, 1);
if (null != emp) {
System.out.println(emp.getId() + " " + emp.getNm());
} else {
System.out.println("Emp doesn't exist..");
}
This code works fine and gives me 1 record, as seen below on console :-
sessionFactory is built.Get session object
Hibernate: select kk0_.id as id0_0_, kk0_.name as name0_0_ from kaushik1 kk0_ where kk0_.id=?
1 kaushik
But when I introduce a Load event listener class through hibernate configuration, the record is not fetched. Rather query itself is not fired.
My Listener class is :-
import org.hibernate.HibernateException;
import org.hibernate.event.LoadEvent;
import org.hibernate.event.LoadEventListener;
public class MyLoadListener implements LoadEventListener {
public void onLoad(LoadEvent arg0, LoadType arg1) throws HibernateException {
System.out.println("inside my own onLoad listener");
}
}
And in my hibernate.cfg.xml I added line :-
<listener type="load" class="com.cts.eventlistener.MyLoadListener"/>
Now when same code is invoked, I can see on console :-
sessionFactory is built.Get session object
inside my own onLoad listener
Emp doesn't exist..
Why is query not getting invoked when onLoad of event listener is called ?
The need to configure DefaultLoadEventListener is bit counter intiutive.
I found a better way in this case for that listener. Instead of implementing LoadEventListener interface we should “extend” DefaultLoadEventListener.
We will override its onLoad() and inside it call super.onLoad(). This worked very well.
And in configuration only configure custom listener.