我将展示我一起使用这些框架的方式。我避免了HibernateTemplate的需要,我认为这个类太有限了,我更喜欢直接使用Session。
一旦你的项目中有Spring,它应该在你的Daos中注入Hibernate SessionFactory,这样你就可以处理Session。首先,你需要配置SessionFactory在你的applicationContext.xml:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
现在你可以用@Autowired注解注入的SessionFactory:
@Repository
public class HibernateProductDao implements ProductDao {
private final SessionFactory factory;
@Autowired
public HibernateProductDao(final SessionFactory factory) {
this.factory = factory;
}
public List<Product> findAll() {
return factory.getCurrentSession().createCriteria(Product.class).list();
}
public void add(final Product product) {
factory.getCurrentSession().save(product);
}
}
这里有一些重要的事情,你应该使用方法getCurrentSession(),因为这样你就可以让Spring控制Session的生命周期。如果你使用getSession()来代替它,它就成为你的责任,例如关闭会话。
现在,让我们配置的Struts 2.在你的web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
您需要的文件struts.xml中也说,春节将制造对象:
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
</struts>
最后,您可以在您的动作中注入Dao:
public class ProductAction {
private ProductDao dao;
@Autowired
public ProductAction(ProductDao dao) {
this.dao = dao;
}
}
当然,由于您使用Spring注释,用component-scan扫描软件包。
这是我发现整合这个框架的最佳方式,我希望这很有帮助。
您的场景是否涉及在UI层上打开Hibernate会话?如果是这样,你应该考虑[Open View in View](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.html)模式。它可以通过Spring轻松配置。 – izilotti
我在问会话休眠(Dao连接 - 查询执行) – softmage99