How to get current Connection object in Spring JDBC
Use DataSourceUtils.getConnection()
.
It returns connection associated with the current transaction, if any.
Obtain the Connection
from the DataSource
bean.
You can access the dataSource by using Spring dependency injection to inject it into your bean, or by accessing ApplicationContext
statically:
DataSource ds = (DataSource)ApplicationContextProvider.getApplicationContext().getBean("dataSource");
Connection c = ds.getConnection();
I'm not sure if this method was available when this question was originally posted, however, it seems the preferred way to do it in the latest version of Spring is with JdbcTemplate
and PreparedStatementCreator
. See https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#query-org.springframework.jdbc.core.PreparedStatementCreator-org.springframework.jdbc.core.PreparedStatementSetter-org.springframework.jdbc.core.ResultSetExtractor- or any of the other query
methods that take a PreparedStatementCreator
as the first param:
jdbcTemplate.query(con -> {
// add required logic here
return con.prepareStatement("sql");
}, rs -> {
//process row
});
This has the advantage over the other provided answers (DataSourceUtils.getConnection()
or jdbcTemplate.getDataSource().getConnection()
as a new connection is not allocated, it uses the same connection management it would as calling any of the other jdbcTemplate
querying methods. You also therefore do not need to worry about closing / releasing the connection, since spring will handle it.
Just an Info : I am using Spring JDBC Template, which holds the current connection object for me, which can be received as follows.
Connection con;
con = getJdbcTemplate().getDataSource().getConnection();