Hibernate 拦截器

非Web请求Hibernate会话管理
本文介绍如何在非Web请求环境下使用HibernateInterceptor配置Hibernate会话,通过TransactionProxyFactoryBean实现事务管理,确保非Web场景下也能正确管理Hibernate会话。
在一个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>

### 整合 Hibernate 拦截器到 Spring Boot 的方法 在 Spring Boot 中整合 Hibernate 拦截器可以用于实现自定义逻辑或审计功能。以下是具体的方法: #### 配置 `LocalSessionFactoryBean` 或 `EntityManagerFactory` 由于 Spring Boot 自动配置了 Hibernate,因此可以通过设置 `hibernate.session_factory.interceptor` 属性来指定拦截器类。 ```properties spring.jpa.properties.hibernate.session_factory.interceptor=com.example.CustomInterceptor ``` 此属性会告诉 Hibernate 使用哪个拦截器实例[^1]。 #### 创建自定义拦截器类 创建一个继承自 `org.hibernate.EmptyInterceptor` 的类,并重写所需的方法。例如: ```java import org.hibernate.EmptyInterceptor; import java.io.Serializable; public class CustomInterceptor extends EmptyInterceptor { @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { // 实现保存前的逻辑 System.out.println("Entity is being saved: " + entity); return super.onSave(entity, id, state, propertyNames, types); } @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { // 实现在删除之前的逻辑 System.out.println("Entity is being deleted: " + entity); super.onDelete(entity, id, state, propertyNames, types); } } ``` 上述代码展示了如何通过覆盖 `onSave` 和 `onDelete` 方法,在实体保存和删除之前执行特定操作。 #### 注册拦截器到 Spring 应用上下文中 如果需要动态注册拦截器,则可以在应用启动时将其注入到 Bean 定义中。例如: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, DataSource dataSource) { Map<String, Object> properties = new HashMap<>(); properties.put("hibernate.session_factory.interceptor", customInterceptor()); return builder.dataSource(dataSource).packages("com.example").persistenceUnit("unitName") .properties(properties).build(); } @Bean public CustomInterceptor customInterceptor() { return new CustomInterceptor(); } } ``` 这段代码显示了如何将拦截器作为 Bean 进行管理并传递给 `entityManagerFactory` 的配置过程[^2]。 #### 测试集成效果 完成以上步骤后,运行应用程序并通过调试验证拦截器是否按预期工作。每次触发数据库交互时,相应的拦截器方法会被调用。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值