Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JdbcTemplate create a new connection every time you call query()?

Tags:

java

mysql

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).

like image 635
ktm5124 Avatar asked Feb 28 '13 05:02

ktm5124


1 Answers

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.

like image 137
Evgeniy Dorofeev Avatar answered Oct 30 '22 21:10

Evgeniy Dorofeev