简体   繁体   English

如何获取jdbcTemplate使用的当前Connection对象

[英]How to get current Connection object used by jdbcTemplate

I am looking for a way to intercept the connection that JDBCTemplate creates internally ie the connection that is created when the function getConnection() is called by JDBCTemplate. 我正在寻找一种方法来拦截JDBCTemplate内部创建的连接,即JDBCTemplate调用函数getConnection()时创建的连接。

ex: if I use jdbcTemplate.update(query); 例如:如果我使用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. 我正在使用C3P0连接池。

Many people have suggested using DataSourceUtils.getConnection() , but that just fetches a new connection from the pool and does not solve my issue. 许多人建议使用DataSourceUtils.getConnection() ,但这只是从池中获取新连接并且不能解决我的问题。

This thread also effectively asks the same question: How to get current Connection object in Spring JDBC 这个线程也有效地提出了同样的问题: 如何在Spring JDBC中获取当前的Connection对象

I am facing the same issue . 我面临同样的问题。 I want to know the current connection the template is using to update or run the queries . 我想知道模板用于更新或运行查询的当前连接。 I tested the below two ways but both of them is returning new connection every time and not the connection that is currently being used to execute the statements? 我测试了以下两种方式,但它们都是每次返回新连接而不是当前用于执行语句的连接?

Connection conn = DataSourceUtils.getConnection(template.getDataSource());
        Connection con=template.getDataSource().getConnection();

@Bean
public DataSource dataSource() throws NamingException {
    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    DataSource dataSource = (javax.sql.DataSource) ctx.lookup(dsnName);
    return dataSource;
}
jdbcTemplate.getDataSource().getConnection();

通过使用上面的行,我们可以获取连接对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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