Hibernate 拦截器

来源:互联网 发布:淘宝网手机版支付宝 编辑:程序博客网 时间:2024/05/19 03:46
在一个spring和hibernate集成的web应用中,一般都使用OpenSessionInViewFilter来提供单一的hibernate连接。
也就是说,只有只能提供给web request的hibernate连接。
如果不是web request需要hibernate连接,怎么办?还是有办法的,使用hibernateInterceptor。

做法是:
1.声明一个hibernateInterceptor,其中的sessionFacory是你的hibernate sessionvFactory的bean名
<!-- Declaration of HibernateInterceptor -->
    <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
         <property name="sessionFactory">
           <ref bean="sessionFactory"/>
         </property>
    </bean>   
2.定义一个模板,声明在什么情况下使用此模板,并且指定和哪些hibernateInterceptor合成
<!-- Manager template  -->
    <bean id="txProxyTemplate" abstract="true"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager" ref="transactionManager"/>
        <property name="transactionAttributes">
            <props>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
                <prop key="remove*">PROPAGATION_REQUIRED</prop>
                <prop key="update*">PROPAGATION_REQUIRED</prop>               
                <prop key="create*">PROPAGATION_REQUIRED</prop>  
                <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
            </props>
        </property>
        <property name="preInterceptors">
            <list>
             <ref bean="hibernateInterceptor"/>
            </list>
        </property>                       
    </bean>
3. 声明一个自定义bean的时候适用模板,这样即可以在web request的时候适用当前hibernate session, 使用其他方式调用,
比如quartz调用的时候,也可以绑定hibernate session。
<!-- Sample Manager that encapsulates business logic -->
    <bean id="userManager" parent="txProxyTemplate">
        <property name="target">
            <bean class="com.acme.service.impl.UserManagerImpl"/>
        </property>
    </bean>