问题
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).
回答1:
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.
来源:https://stackoverflow.com/questions/9267815/does-the-spring-transaction-manager-bind-a-connection-to-a-thread