Hibernate 中的会话和连接有什么区别?

What is the difference between a Session and a Connection in Hibernate?

我要清除基础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(会话绑定到单个逻辑@Transaction 和一个物理数据库事务的生命周期)
  • 长会话(会话可以跨越多个@Transaction 操作,因此涉及多个数据库事务)

谈到数据库事务,有两种不同的方法:

  • RESOURCE_LOCAL 事务,使用单个 DataSource 将始终将物理数据库事务绑定到 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 会话已重新连接,flushing/committing 可以继续。

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

默认情况下,当您提交事务时,Session 会关闭,底层连接也会关闭。如果使用连接池,数据库连接确实会return到池中。

  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 is now controlled by the connection release modes.