使用Spring和JAX-WS进行Hibernate会话管理

时间:2011-04-18 13:41:07

标签: hibernate spring jax-ws

我有一个使用Hibernate进行持久化的应用程序,并尝试实现JAX-WS接口(使用Spring Framework公开它)。我还有一个服务类(注释为@WebService@WebMethod),它调用持久层中的方法。在处理延迟加载的对象时,我得到异常(LazyInitializationException)。

我遇到了与Quartz作业相同的问题,并且能够通过用org.springframework.aop.framework.ProxyFactoryBean包装我的作业bean并提供org.springframework.orm.hibernate3.HibernateInterceptor来解决它。我试图用ProxyFactoryBean包装我的服务bean,但是收到的错误是关于代理不是带注释的Web服务。

在这种情况下,有没有办法做同样类型的事情,或者在这种情况下管理我的hibernate会话的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

因此,看起来一个潜在的选择是将我的实现分成两个类。一个将包含调用数据库持久层的所有业务逻辑,另一个将公开Web服务并调用业务逻辑。包含业务逻辑的类可以用Spring框架ProxyFactoryBean包装,以使用HibernateInterceptor

爪哇:

public class BusinessLogicClass implements MyInterface {
  public void doBusinessLogic() {
    //Perform Hibernate stuff here
  }
}

@WebService
public class WebServiceClass {
  BusinessLogicClass blc;

  public setBlc(BusinessLogicClass blc) {
    this.blc = blc;
  }

  @WebMethod
  public void doLogic() {
    blc.doBusinessLogic()
  }
}

Spring XML配置:

<bean id="transactionalService" class="BusinessLogicClass">
</bean>

<bean id="transactionalServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
        <ref bean="transactionalMessageQueueService"/>
    </property>
    <property name="proxyInterfaces">
        <value>MyInterface</value>
    </property>
    <property name="interceptorNames">
        <value>hibernateInterceptor</value>
    </property>
</bean>

<bean id="webService" class="WebServiceClass">
    <property name="blc">
        <ref bean="transactionalServiceProxy"/>
    </property>
</bean>

这确实解决了我的问题。虽然对于我的应用程序来说,使用基本相同的方法的两个类只是让持久性工作...但是有点烦恼...

- 更新 -

作为替代(可能是更好的替代方案),在Spring XML文件中使用代理配置可以启用基于注释的转换管理,然后可以对需要在事务中的BusinessLogicClass中的每个方法进行注释与@Transactional。这是我最终使用的方法。