Hibernate框架 – 为什么一个会话不够

huangapple go评论73阅读模式
英文:

Hibernate framework - why one session is not enough

问题

我现在正在使用Java中的Hibernate框架,并且我需要理解为什么我们应该为每个过程使用一个会话。为什么不可以为整个程序使用一个全局会话呢?

英文:

I am now working with the Hibernate framework in Java and I need to understand why we should use one session for every process. Why don't we use one global session for the whole program?

答案1

得分: 1

你不需要为一个进程使用一个会话,而是为一个线程,在某一个时间点上使用一个会话。限制应该放在线程上,而不是进程上。在JVM进程中,可以有多个线程使用数据库连接池。在使用连接池时,连接在多个线程之间被重用,这样事务边界就不会重叠,这也是使用一个会话即线程的连接的主要思想。请参阅事务和并发控制

英文:

You don't need to use one session for a process but for a thread and that too at one point of time. The restriction should be on threads, not processes. In a JVM process there can be multiple threads using a database connection pool. When using a connection pool connections are reused between threads in such a way that transaction boundaries are not overlapped which is the main idea of using one session ie. connection for a thread. See Transactions and concurrency control

答案2

得分: 1

会话用于与数据库建立物理连接。会话对象轻量级,并设计为每次需要与数据库进行交互时实例化。持久化对象通过会话对象保存和检索。

会话对象不应该保持长时间打开,因为它们通常不是线程安全的,应该根据需要创建和销毁它们。会话的主要功能是为映射实体类的实例提供创建、读取和删除操作。

英文:

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer, create, read, and delete operations for instances of mapped entity classes.

huangapple
  • 本文由 发表于 2020年10月2日 09:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64165063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定