【问题标题】:Close session connection in Hibernate在 Hibernate 中关闭会话连接
【发布时间】:2017-05-16 12:37:34
【问题描述】:

这是我的 Hibernate 条件查询:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(myclass.class, "b");
ProjectionList properties = Projections.projectionList();
listArr = criteria.setResultTransformer(Transformers.aliasToBean(HashMap.class)).list();

我想在执行查询后关闭会话连接。

【问题讨论】:

  • 如果你想关闭会话,你很可能不再访问数据库,因此你可以简单地关闭 sessionFactory
  • 我已经尝试过 sessionFactory.close() 但连接仍然处于空闲状态。
  • 试试sessionFactory.getCurrentSession().flush(); sessionFactory.getCurrentSession().disconnect(); sessionFactory.getCurrentSession().close(); sessionFactory.close();
  • 感谢您的回复。我已经尝试过这些但仍然连接不关闭。连接将在一段时间后关闭。

标签: java hibernate session hibernate-criteria


【解决方案1】:

您正在使用 sessionFactory.getCurrentSession(),因此您无需刷新和关闭会话。它会在事务结束时自动刷新并关闭。

更多

getCurrentSession

当你调用 SessionFactory. getCurrentSession,它将为您提供在休眠上下文中并由休眠内部管理的会话对象。它绑定到事务范围。 当你调用 SessionFactory. getCurrentSession ,如果不存在则创建一个新会话,否则使用当前休眠上下文中的相同会话。

openSession

当您调用 SessionFactory.openSession 时,它总是会重新创建新的 Session 对象并将其提供给您。您需要显式刷新和关闭这些会话对象。由于会话对象不是线程安全的,因此您需要在多线程环境中为每个请求创建一个会话对象,在 Web 应用程序中也需要为每个请求创建一个会话。

如果你在单线程环境中使用休眠,你可以使用getCurrentSession

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多