getConnection与DataSource

getConnection与DataSource

本文介绍了DataSourceUtils.getConnection与DataSource.getConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在spring上下文中初始化了datasource bean。我想知道应该采用什么方式?为什么我只是不能写dataSource.getConnection()?

I have datasource bean initialized in the spring context. I wonder what way should be used? Why I just can not write dataSource.getConnection()?

推荐答案

有一个重要区别: dataSource .getConnection()始终返回从dataSource或连接池获取的新连接。 DataSourceUtils.getConnection()检查当前线程是否存在活动事务。如果有,它将返回与此事务的连接。如果没有,它的行为与 dataSource.getConnection()完全相同。

There is one important difference: dataSource.getConnection() always returns a new connection obtained from the dataSource or connection pool. DataSourceUtils.getConnection() checks if there is an active transaction for the current thread. If there is one, it will return connection with this transaction. If there is none it will behave exactly the same way as dataSource.getConnection().

你需要成为使用 DataSourceUtils.getConnection()时要小心。如果它返回活动事务的连接,则意味着其他人将关闭它,因为它是谁打开事务的责任。另一方面,如果它从dataSource返回一个全新的连接,那么你应该提交/回滚/关闭它。

You need to be careful when using DataSourceUtils.getConnection(). If it returns connection for the active transaction it means someone else will be closing it since it's the responsibility of whoever opened the transaction. On the other hand, if it returns a brand new connection from the dataSource it's you who should commit/rollback/close it.

这篇关于DataSourceUtils.getConnection与DataSource.getConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 03:09