翻譯的這篇文章包含了好幾個知識點,雖然短了點兒,但是非常有用。
1.spring
2.hibernate
3.quartz--定時調度工具,spring已經做了封裝,也可以單獨使用。
4.OpenSessionInViewFilter--web框架下的一個filter,能夠讓web request使用單一的hibernate session。
有的j2ee項目在web.xml文件中添加了OpenSessionInViewFilter,其目的是給web request提供單一的hibernate session,但是它也只能給web request提供hibernate session。也就是說,如果有某一個hibernate請求不是經由web request發起的,而是由quartz這樣的定時任務發起的,那麼quartz怎麼樣才能得到hibernate session呢?
解決辦法就是使用HibernateInterceptor。當quartz發起hibernate session請求時,HibernateInterceptor會提供一個hibernate session給它。
配置文件如下:
- <!-- Declaration of HibernateInterceptor -->
- <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
- <property name="sessionFactory">
- <ref bean="sessionFactory"/>
- </property>
- </bean>
- <!-- 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>
- <!-- Sample Manager that encapsulates business logic -->
- <bean id="userManager" parent="txProxyTemplate">
- <property name="target">
- <bean class="com.acme.service.impl.UserManagerImpl" autowire="byName"/>
- </property>
- </bean>
其中,<!-- Declaration of HibernateInterceptor -->部分定義了HibernateInterceptor;
<!-- Manager template -->部分定義了模板,並且加入了HibernateInterceptor;
<!-- Sample Manager that encapsulates business logic -->部分定義業務邏輯中的bean,記住,一定讓他使用模板。
譯者言:
1.這樣做使得非web request可以使用j2ee資源。
2.我的做法和上面有些差別,但是也成功了。 我的做法是:
我沒有定義<!-- Declaration of HibernateInterceptor -->這一部分,只定義了模板,在添加bean的時候使用模板。
原文如下:
Using HibernateInterceptor to bind Hibernate Sessions for Quartz jobs in Spring
I use the OpenSessionInViewFilter to provide a single Hibernate Session for each request to my Spring webapplications. It works transparently and well, but only for web requests. So how do you provide a Hibernate Session to your background jobs (like Quartz scheduled jobs)?
I wire a HibernateInterceptor into my proxy template for all the managers in my application. With this configuration, when Quartz fires up a job and makes a call to the manager/service layer the HibernateInterceptor binds a Hibernate Session to the background thread. Beautiful.
It looks something like this:(代碼同上)