java - 什么是数据库 session ?

标签 java hibernate session transactions

我对数据库事务的概念有一个大致的了解。我们在事务中访问数据库以确保 ACID 属性。

在 Hibernate 中有一个称为 session 的概念。 session 有什么用?何时应该在两个 session 中而不是在同一个 session 中访问数据库?

为了解释更多,我看到了 hibernate 代码

  • 从 session 工厂获取 session
  • 打开一个 session
  • 开始交易
  • 提交事务
  • 关闭 session

我需要知道的是,这里的 session 的重要性是什么?为什么不用事务工厂之类的东西,开始事务并提交事务?

最佳答案

session 不仅仅是一个事务,它是 UnitOfWork 的实现。图案。换句话说,它保留加载的对象,知道哪些对象必须被持久化等:

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

为了更好地理解 Session 和 Transaction 之间的关系,您可以查看 this article .

A single Hibernate Session might have the same scope as a single database transaction.

This is the most common programming model used for the session-per-request implementation pattern. A single Session and a single database transaction implement the processing of a particular request event (for example, a Http request in a web application). Do never use the session-per-operation anti-pattern! (There are extremely rare exceptions when session-per-operation might be appropriate, you will not encounter these if you are just learning Hibernate.)

Another programming model is that of long Conversations, e.g. an application that implements a multi-step dialog, for example a wizard dialog, to interact with the user in several request/response cycles. One way to implement this is the session-per-request-with-detached-objects pattern. Once persistent objects are considered detached during user think-time and have to be reattached to a new Session after they have been modified.

The session-per-conversation pattern is however recommended. In this case a single Session has a bigger scope than a single database transaction and it might span several database transactions. Each request event is processed in a single database transaction, but flushing of the Session would be delayed until the end of the conversation and the last database transaction, to make the conversation atomic. The Session is held in disconnected state, with no open database connection, during user think-time. Hibernate's automatic optimistic concurrency control (with versioning) is used to provide conversation isolation.

关于java - 什么是数据库 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10521947/

相关文章:

java - 即使将 Border 设置为 EmptyBorder,JButton 的边框也不会消失

java - 使 JPA 在 JBoss 服务器上与 Spring Framework 一起工作

hibernate - Hibernate 是否支持嵌套事务?

.net - 系统事件和从 sleep 状态恢复

c# - Internet Explorer - 通过客户端 Java 或 C# 代码设置 session Cookie 来指定 JSessionID

java - 在 session 中更改 java bean 中的某些属性

java - JFrame 不 dispose()

java - 保证 Solr 提交已经发生

无线程实现Runnable的Java类

java - 使用 IN 的格式错误的查询