gpt4 book ai didi

java - Hibernate 中的 beginTransaction 是否分配新的数据库连接?

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:53 26 4
gpt4 key购买 nike

只是想知道在 Hibernate 中开始一个新事务是否真的分配了一个到数据库的连接?

我担心 b/c 我们的服务器会为收到的每个请求开始一个新事务,即使该请求不与数据库交互。我们发现数据库连接是一个主要瓶颈,所以我想知道我是否应该花时间缩小我的交易范围。

四处搜索,未能找到合适的答案。非常简单的代码在这里:

    SessionFactory sessionFactory = (SessionFactory) Context.getContext().getBean("sessionFactory");
sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);

非常感谢!一个

最佳答案

根据 11.1. Session and transaction scopes 部分Hibernate 文档:

A SessionFactory is an expensive-to-create, threadsafe object, intended to be shared by all application threads. It is created once, usually on application startup, from a Configuration instance.

A Session is an inexpensive, non-threadsafe object that should be used once and then discarded for: a single request, a conversation or a single unit of work. A Session will not obtain a JDBC Connection, or a Datasource, unless it is needed. It will not consume any resources until used.

In order to reduce lock contention in the database, a database transaction has to be as short as possible. Long database transactions will prevent your application from scaling to a highly concurrent load. It is not recommended that you hold a database transaction open during user think time until the unit of work is complete.

现在,回答你的问题:

  • 获取Session 不会立即获取连接(连接是延迟加载的)
  • 但调用 beginTransaction() 将导致给定 Session 的连接加载
  • 后续调用将重用相同的连接

查看 org.hibernate.impl.SessionImpl#beginTransaction() 并查看代码以获取更多详细信息。

关于java - Hibernate 中的 beginTransaction 是否分配新的数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2540245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com