hibernate - Hibernate 中的 session 和连接有什么区别?

标签 hibernate session jpa database-connection connection-pooling

我想清除基本的3点,

Does beginning a new database transaction on an old session obtains a new connection and resumes the session?

Does committing a database transaction disconnects a session from the JDBC connection and returns the connection to the pool?

From Hibernate Documentation, earlier versions of Hibernate required explicit disconnection and reconnection of a Session. These methods are deprecated, asbeginning and ending a transaction has the same effect. How do they have the same effect?

最佳答案

Hibernate Session 只是一个事务性的后写缓存,它将实体状态转换转换为 DML 语句。 Hibernate Session 可以与数据库连接或断开连接。当它断开连接时,它无法将当前挂起的实体状态更改刷新到底层数据库。
associate a Hibernate Session to a database transaction有多种方式:

  • session-per-request( session 绑定(bind)到单个逻辑@Transaction 和一个物理数据库事务的生命周期)
  • 长对话( session 可以跨越多个@Transaction 操作,因此涉及多个数据库事务)

  • 对于数据库事务,有两种不同的方法:
  • RESOURCE_LOCAL 事务,使用单个 DataSource 将始终将物理数据库事务绑定(bind)到 Hibernate Session(在单个逻辑事务的上下文中,这意味着您仍然可以实现长对话以跨越多个此类逻辑事务)。
  • JTA,使用多个数据源。 JTA 声明应该在每个语句之后积极释放连接,但实际上,在单个逻辑事务的上下文中您仍然可以获得相同的 JDBC 连接句柄。

  • 现在回到你的问题:
    1. Does beginning a new database transaction on an old session obtains a new connection and resumes the session?

    是的。 Hibernate session 重新连接并且可以继续刷新/提交。
    1. Does committing a database transaction disconnects a session from the JDBC connection and returns the connection to the pool?

    默认情况下,当您提交事务时, session 关闭,底层连接关闭。如果使用连接池,数据库连接确实会返回池中。
    1. From Hibernate Documentation, earlier versions of Hibernate required explicit disconnection and reconnection of a Session. These methods are deprecated, as the beginning and ending of a transaction have the same effect. How do they have the same effect?

    这些方法已被弃用,因为 connection management现在由 connection release modes 控制.

    关于hibernate - Hibernate 中的 session 和连接有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28486850/

    相关文章:

    java - Jtwig 如何获取HttpSession/HttpServletRequest?

    session - JSESSIONID 和 hazelcast.sessionId

    python - 在 Django View 之间发送数据

    java - 查找多个子类的不同属性

    java - JPA 不插入数据库,为什么?

    java - hibernate 列名问题

    Java 应用程序在运行我的代码后不会关闭

    oracle - 如何在 HQL 查询中使用 native sql 函数?

    java - jsp页面配置错误: Not able to redirect to my home.

    sql - JPA with Hibernate - 多对多关系,获取所有数据