How to get current Connection object in Spring JDBC

后端 未结 4 2049
暖寄归人
暖寄归人 2020-12-09 01:44

How can I get the current Connection object for an Oracle database? I\'m using the JDBC module in Spring 3.0.5.

相关标签:
4条回答
  • 2020-12-09 02:20

    Use DataSourceUtils.getConnection().

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

    0 讨论(0)
  • 2020-12-09 02:26

    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();
    
    0 讨论(0)
  • 2020-12-09 02:29

    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();
    
    0 讨论(0)
  • 2020-12-09 02:34

    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.

    0 讨论(0)
提交回复
热议问题