如何在Hibernate中打开查询执行会话

时间:2013-01-03 13:27:59

标签: spring hibernate session

我在我的项目中使用struts2-spring-hibernate。 我正在通过spring处理数据库连接,所以我不需要hibernate.cfg.xml 我需要执行我的查询,我需要结果

我通过使用这些方法成功获得了结果

手动打开和关闭会话: 1.会话会话= sessionFactory.openSession(); 2. Session newSession = HibernateUtil.getSessionFactory()。openSession();

不能手动处理会话 1. getHibernateTemplate()。find(); 2. getSession()。createSQLQuery();

我不知道哪种方法最好,请建议我哪一种方法最适合会议

会话将由getHibernateTemplate()和getSession()打开和关闭。

1 个答案:

答案 0 :(得分:0)

我将展示我一起使用这些框架的方式。我避免需要HibernateTemplate,我认为这个类太有限了,我更喜欢直接使用Session。

一旦你的项目中有Spring,它应该在你的Daos中注入Hibernate SessionFactory,这样你就可以处理Session了。首先,您需要在applicationContext.xml中配置SessionFactory:

<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(),它就会成为你的责任,例如,关闭Session。

现在,让我们配置Struts 2.在你的web.xml中:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

你也需要文件struts.xml,说Spring会编造对象:

<!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扫描包。

这是我发现整合这个框架的最佳方式,我希望它有用。