【问题标题】:how to open session for query execution in Hibernate如何在 Hibernate 中打开会话以执行查询
【发布时间】:2013-01-03 13:27:58
【问题描述】:

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

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

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

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

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

会话何时通过 getHibernateTemplate() 和 getSession() 打开和关闭。

【问题讨论】:

  • 您的场景是否涉及在 UI 层打开 Hibernate 会话?如果是这样,您应该考虑Open Session in View 模式。它可以通过 Spring 轻松配置。
  • 我正在请求会话进行休眠(Dao 连接 - 查询执行)

标签: spring hibernate session


【解决方案1】:

我将展示我如何一起使用这些框架。我避免需要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>

最后,你可以在你的行动中注入道:

public class ProductAction {

    private ProductDao dao;

    @Autowired
    public ProductAction(ProductDao dao) {
        this.dao = dao;
    }
}

当然,由于你使用的是Spring注解,你需要扫描带有component-scan的包。

这是我发现的集成此框架的最佳方式,希望对您有所帮助。

【讨论】:

  • 嗨,我没有使用休眠注释。
  • 这不是问题,在这个例子中我只使用了弹簧注解。
  • k 谢谢,插入和更新,需要事务提交吗?
  • 您可以配置 HibernateTransactionManager 类,Spring 会为您完成。然后,您需要在方法中使用注释 @Transactional 进行插入和更新,并在搜索方法中使用 @Transactional(readOlny = true)。这样你就不用担心控制事务了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多