【问题标题】:spring/hibernate: open/close session each time VS getCurrentSessionspring/hibernate:每次打开/关闭会话 VS getCurrentSession
【发布时间】:2013-03-06 20:05:53
【问题描述】:

这些方法之间有什么区别,哪一种更好?到目前为止,我的代码如下:

public void delete(Song song) {
    session = sessionFactory.getCurrentSession();
    session.delete(song);
    session.flush();
}

但在运行上述代码时,记录并不总是被删除(准确地说:id=1 永远不会被删除,其他 id 总是被删除)。我读到保持打开的会话会稍微加快应用程序的速度——这就是我共享会话对象的原因。我的业务对象通过 DI 获取会话工厂:

@Autowired
private SessionFactory sessionFactory;

Session session = null;

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

【问题讨论】:

    标签: spring hibernate session


    【解决方案1】:

    根据我对 Hibernate 的经验,我得出的结论是,最好的策略是将 Hibernate 会话生命周期与单个事务的持续时间相匹配。根据您的具体需求,您可能需要做其他事情,但我敢打赌,所提出的策略在 95% 的实际案例中都有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 2012-08-04
      • 2014-01-28
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多