How to get current Connection object in Spring JDBC

后端 未结 4 2068
暖寄归人
暖寄归人 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: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.

提交回复
热议问题