![](/img/trans.png)
[英]jdbc connection with java, singleton connection object or spring jdbc connection?
[英]How to get current Connection object in Spring JDBC
如何獲取Oracle數據庫的當前Connection對象? 我在Spring 3.0.5中使用JDBC模塊。
從DataSource
bean獲取Connection
。
您可以通過使用Spring依賴注入將其注入到bean中,或者通過靜態訪問ApplicationContext
來訪問dataSource:
DataSource ds = (DataSource)ApplicationContextProvider.getApplicationContext().getBean("dataSource");
Connection c = ds.getConnection();
使用DataSourceUtils.getConnection()
。
它返回與當前事務關聯的連接(如果有)。
只是一個信息:我正在使用Spring JDBC Template,它為我保存當前的連接對象,可以按如下方式接收。
Connection con;
con = getJdbcTemplate().getDataSource().getConnection();
我不確定這個問題最初是否發布時是否可用,但是,最新版本的Spring中使用JdbcTemplate
和PreparedStatementCreator
的首選方法似乎也是如此。 請參閱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
});
這比其他提供的答案( DataSourceUtils.getConnection()
或jdbcTemplate.getDataSource().getConnection()
作為新連接沒有分配優勢,它使用與調用任何其他jdbcTemplate
查詢方法相同的連接管理。因此,您也不必擔心關閉/釋放連接,因為spring會處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.