DataSourceUtils.getConnection vs DataSource.getConnection

I have a bean data source initialized in the context of spring. I wonder which method should be used? Why can't I just write dataSource.getConnection ()?

+7
source share
2 answers

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.

+14
source

DataSourceUtils#getConnection() pretty clearly documents why you can use it: in particular, it uses the Spring JDBC exception hierarchy as opposed to raw SQL exceptions, and it will participate in Spring transaction management. If you do not need either of these two functions, you can simply use DataSource#getConnection() and continue with your code.

+2
source

Source: https://habr.com/ru/post/910383/


All Articles