[英]How to get current Connection object in Spring JDBC
How can I get the current Connection object for an Oracle database? 如何获取Oracle数据库的当前Connection对象? I'm using the JDBC module in Spring 3.0.5. 我在Spring 3.0.5中使用JDBC模块。
Obtain the Connection
from the DataSource
bean. 从DataSource
bean获取Connection
。
You can access the dataSource by using Spring dependency injection to inject it into your bean, or by accessing ApplicationContext
statically: 您可以通过使用Spring依赖注入将其注入到bean中,或者通过静态访问ApplicationContext
来访问dataSource:
DataSource ds = (DataSource)ApplicationContextProvider.getApplicationContext().getBean("dataSource");
Connection c = ds.getConnection();
Use DataSourceUtils.getConnection()
. 使用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. 只是一个信息:我正在使用Spring JDBC Template,它为我保存当前的连接对象,可以按如下方式接收。
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
. 我不确定这个问题最初是否发布时是否可用,但是,最新版本的Spring中使用JdbcTemplate
和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: 请参阅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-或将PreparedStatementCreator
作为第一个参数的任何其他query
方法:
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. 这比其他提供的答案( DataSourceUtils.getConnection()
或jdbcTemplate.getDataSource().getConnection()
作为新连接没有分配优势,它使用与调用任何其他jdbcTemplate
查询方法相同的连接管理。因此,您也不必担心关闭/释放连接,因为spring会处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.