There is one important difference: dataSource.getConnection()
always returns a new connection obtained from the dataSource pool or connection pool. DataSourceUtils.getConnection()
checks if an active transaction exists for the current thread. If it is, it will return a connection to this transaction. If not, it will behave exactly like dataSource.getConnection()
.
You need to be careful when using DataSourceUtils.getConnection()
. If he returns a connection for an active transaction, it means that someone else will close it, since it is the responsibility of the person who opened the transaction. On the other hand, if it returns a completely new connection to the dataSource, then you must commit / roll back / close it.
source share