Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current Connection object in Spring JDBC

How can I get the current Connection object for an Oracle database? I'm using the JDBC module in Spring 3.0.5.

like image 797
vlcik Avatar asked Dec 08 '11 08:12

vlcik


People also ask

How can I get current connection in spring boot?

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.

What is connection object in JDBC?

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.

How do you find the ResultSet from JdbcTemplate?

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.


3 Answers

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(); 
like image 99
socha23 Avatar answered Sep 23 '22 20:09

socha23


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(); 
like image 43
Arun GK Avatar answered Sep 20 '22 20:09

Arun GK


Use DataSourceUtils.getConnection().

It returns connection associated with the current transaction, if any.

like image 21
axtavt Avatar answered Sep 22 '22 20:09

axtavt