Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

We had an interceptor that was written for Hibernate 3. When we went to Hibernate 4, we discovered that methods that we were used to using didn’t exist anymore. The original Hibernate 3 code looked like:

Session session = null;
MySQLMatchingRowCountInterceptor interceptor = new MySQLMatchingRowCountInterceptor();
session = ((Session) getROEntityManager().getDelegate()).getSessionFactory().openSession(interceptor);
session.beginTransaction();
interceptor.initialize(session);

Unfortunately, SessionFactory.openSession() no longer takes an interceptor.

To define an interceptor, you need to create the Session from the SessionFactory with the .withOptions() method. Once you do that, you can specify the interceptors.

Session session = null;
MySQLMatchingRowCountInterceptor interceptor = new MySQLMatchingRowCountInterceptor();
session = ((Session) getROEntityManager().getDelegate()).getSessionFactory()
                                                        .withOptions()
                                                        .interceptor(interceptor)
                                                        .openSession();
session.beginTransaction();
interceptor.initialize(session);

The Maven dependency we were using for Hibernate 4.3.11 is:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate.version}</version>
</dependency>

October 11th, 2016

Posted In: hibernate, Java, java ninja, Javaninja

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com