Saturday, August 14, 2010

Spring: Using Hibernate Interceptor

Hibernate is a powerful OR framework and works really well with Spring. In Hibernate you define your entities and queries in HQL (you could also have native SQL). Most of the heavy lifting is done by Hibernate but sometimes you may need to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. For example you may want to dynamically change the SQL generated by Hibernate.

Hibernate Interceptor:
Enter Hibernate Iterceptor. Hibernate Iterceptor provides an API which one can implement to intercept various operation like save and delete of an entity.

Typically it is better to extend EmptyInterceptor and override the methods which you want to implement.


public class HibernateInterceptor extends EmptyInterceptor {
   /* (non-Javadoc)
    * @see org.hibernate.EmptyInterceptor#onPrepareStatement(java.lang.String)
    *
    @Override
    public String onPrepareStatement(String sql) {
    }
}


Spring Hibernate Interceptor:

In Spring you can easily use easily use Hibernate Interceptor by using AnnotationSessionFactoryBean or super class LocalSessionFactoryBean which defines setEntityInterceptor(org.hibernate.Interceptor entityInterceptor) API. Here is an example of how to use it in Spring xml configuration.



<!-- Define an Interceptor -->

<bean id="myInterceptor" class="com.example.HibernateInterceptor"/>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >    
    <property name="dataSource" ref="myDataSource"/>

    <!-- Refer to Interceptor Here -->
    <property name="entityInterceptor">
        <ref bean="myInterceptor"/>
    </property>

    <property name="mappingResources">
        <value>example/persistence/hibernate/customer-dao-named-queries.hbm.xml</value>
    </property>

    <property name="annotatedClasses">
    <!-- fully qualified model class names -->
        <value>com.example.persistence.model.Customer</value>
    </property>

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>





Promote your blog

1 comment:

  1. Thanks for the clear presentation, Can we write this interceptors for specific entities alone

    ReplyDelete