How can I get the current Connection object for an Oracle database? I'm using the JDBC module in Spring 3.0.5.
To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.
When you connect to a data source by either connection method, you create a Connection object, which represents the connection to the data source. You use this Connection object to do the following things: Create Statement, PreparedStatement, and CallableStatement objects for executing SQL statements.
Usage. Step 1 − Create a JdbcTemplate object using a configured datasource. Step 2 − Use JdbcTemplate object methods to make database operations while parsing the resultset using ResultSetExtractor.
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();
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();
Use DataSourceUtils.getConnection()
.
It returns connection associated with the current transaction, if any.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With