简体   繁体   中英

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.

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();

Use DataSourceUtils.getConnection() .

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

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM