7

I am looking for a way to intercept the connection that JDBCTemplate creates internally i.e. the connection that is created when the function getConnection() is called by JDBCTemplate.

ex: if I use jdbcTemplate.update(query); I want to get the information of the connection that was used to complete this update statement. Is there a way to see the metadata of the connection mid or post execution of this statement ? I am using C3P0 connection pool.

Many people have suggested using DataSourceUtils.getConnection() , but that just fetches a new connection from the pool and does not solve my issue.

This thread also effectively asks the same question: How to get current Connection object in Spring JDBC

Utkarsh Shekhar
  • 139
  • 1
  • 8
  • https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#execute-org.springframework.jdbc.core.ConnectionCallback-, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/ConnectionCallback.html – JB Nizet Jun 23 '17 at 05:20

1 Answers1

4
jdbcTemplate.getDataSource().getConnection();

By using the above line we can fetch the connection object.

shizhen
  • 12,251
  • 9
  • 52
  • 88
Sajith
  • 144
  • 1
  • 4
  • 1
    that would return *a* connection, but would that be the same connection that the jdbcTemplate uses for its next operation? – xpmatteo Dec 13 '20 at 15:26
  • If you get a connection in this way, it will generate a connection leak, so you have to close it manually. If you use DataSourceUtils.getConnection() and you are in spring transaction context you will get a same transaction as when you call jdbcTemplate. – Dániel Kis Feb 04 '22 at 07:23