Spring事务管理器是否将连接绑定到线程?

发布于 2025-01-05 00:10:51 字数 502 浏览 5 评论 0原文

我发现以下线程: JdbcTemplate 与 TransactionManager 究竟如何协同工作?

其中第一句话是:

据我了解,DataSourceTransactionManager 将指定 DataSource 的 JDBC 连接绑定到当前线程,允许每个 DataSource 有一个线程绑定连接。如果它是一个连接池,它将占用可用连接之一。

...这正是我想知道的。

使用事务管理器时,最终每个线程都会有自己的单个连接吗?另外,该连接的寿命有多长?同一线程在单个请求中是否使用相同的连接,或者是否发生了其他情况?我只是想了解当你有事务管理器和没有事务管理器时(无论你是否实际上有事务)Spring 到底在做什么。

I found the following thread: How exactly JdbcTemplate with TransactionManager works together?

The first sentence of that:

As far as I understood DataSourceTransactionManager binds a JDBC connection from the specified DataSource to the current thread, allowing for one thread-bound Connection per DataSource. If it's a pool of connections, it will take one of the available connections.

... is exactly what I want to know.

When using a transaction manager, do you end up with each thread having it's own single connection? Also, how long does that connection live? Does the same thread use the same connection throughout a single request, or is there something else going on? I'm just trying to understand what exactly Spring is doing underneath when you have a transaction manager and when you don't (regardless of whether or not you actually have a transaction).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨小沫ゞ 2025-01-12 00:10:52

当使用事务管理器时,您最终会发现每个线程都有自己的单个连接吗?另外,该连接的寿命有多长?

连接一般是从连接池中获取的。当事务管理器启动事务时,连接从池中借用,然后在事务完成时返回到池中。在此期间,连接绑定到线程。

同一线程在单个请求中是否使用相同的连接

它在事务持续时间内使用相同的连接。请求本身是无关紧要的。

无论您是否实际进行了交易

无论您是否明确进行交易,您总是进行交易。如果您没有显式配置,则 JDBC 驱动程序和数据库将启动并完成一项操作,时间与执行单个操作所需的时间相同。 Spring 的事务管理(或任何其他框架的事务管理)使您可以跨多个操作延长该事务的生命周期。这样做需要在事务期间独占使用该连接。

When using a transaction manager, do you end up with each thread having it's own single connection? Also, how long does that connection live?

The connection is generally obtained from a connection pool. The connection is borrowed from the pool when the transaction manager starts the transaction, and then returned to the pool when the transaction finishes. During that time, the connection is bound to the thread.

Does the same thread use the same connection throughout a single request

It uses the same connection for the duration of the transaction. The request itself is irrelevant.

regardless of whether or not you actually have a transaction

You always have a transaction, whether you do it explicitly or not. If you don't configure one explicitly, then the JDBC driver and database will start and finish one for as long as it takes to perform the single operation. Spring's transaction management (or any other framework's transaction management) lets you extend the lifetime of that transaction across multiple operations. Doing so requires exclusive use of the connection for the duration of the transaction.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文