How can I get the current Connection object for an Oracle database? I'm using the JDBC module in Spring 3.0.5.
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();
DataSourceUtils.getConnection()
each time you run one of its methods. It doesn't keep a reference to the connection used last time, so I don't think there is a way to get it. –
Interpolation 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();
JdbcTemplate
can be injected as field easily: @Autowired JdbcTemplate jdbcTemplate;
–
Acetanilide Use DataSourceUtils.getConnection()
.
It returns connection associated with the current transaction, if any.
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.
© 2022 - 2024 — McMap. All rights reserved.