7

In the below example, does JdbcTemplate create two connections or one?

public class MyDao {

     private JdbcTemplate jdbcTemplate;

     public List<Data1> getData1() {
          return jdbcTemplate.query(mySql, myParams, myCallback);
     }

     public List<Data2> getData2() {
          jdbcTemplate.query(mySql2, myParams2, myCallback2);
     }
}

public class Main {
    public static void main(String[] args) {
         MyDao dao = new MyDao();
         List<Data1> d1 = dao.getData1();
         List<Data2> d2 = dao.getData2();
         doStuff(d1, d2);
    }
}

That is to say, does it reuse the connection from the first query? We are assuming that it was constructed with a basic data source (not a pooled data source).

ktm5124
  • 11,861
  • 21
  • 74
  • 119

1 Answers1

9

It depends on the JdbcTempate's DataSource. If you provided a connection pool, like Apache commons-dbcp, then DBCP will do its best to reuse Connections. If you used Spring JDBC's DriverManagerDataSource a new Connection will be created / closed on each JdbcTemplate.query call.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • I see. The data source I had in mind (as you guessed correctly) is Spring's DriverManagerDataSource. You mention Apache DBCP... can you tell me, is this a big improvement over C3P0? I'm aware that C3P0 is no longer being maintained. – ktm5124 Feb 28 '13 at 05:30
  • I dont think i can explain the difference better than http://stackoverflow.com/questions/520585/connection-pooling-options-with-jdbc-dbcp-vs-c3p0 – Evgeniy Dorofeev Feb 28 '13 at 05:38