1

Everytime you use spring JdbcTemplate, does it actually create a new connection to the sql server ?

Mr Matrix
  • 1,128
  • 2
  • 14
  • 28

2 Answers2

3

Understanding datasource interface is the key to understanding the answer to this question. JdbcTemplate has a dependency on datasource and official javadoc for DataSource interface says:

Datasource is a factory for connections to the physical data source that this datasource object represents.

It means every-time a JdbcTemplate is used for executing a SQL query, it requests a connection from the datasource. Datasource retrieves a connection from the connection pool, if available, and gives it to JdbcTemplate. JdbcTemplate then executes the SQL query and releases the connection back to the pool.

So, yes, we would need a new connection every-time JdbcTemplate is used for executing a SQL query but that connection is always fetched from the connection pool that any implementation of Datasource interface maintains.

Maintaining a connection pool is lot more time efficient than creating a new connection on demand. Obviously, considering memory limits, there has to be an upper cap on the connection pool size.

Mr Matrix
  • 1,128
  • 2
  • 14
  • 28
2

Answer 1:

In short yes it does close the connection. The long answer it depends.

When you don’t have a Spring managed transaction then yes the JdbcTemplate will call the close() method on the Connection. However if there was already a connection available due to Springs transaction management closing the connection will be handled by Springs transaction support, which in turn also will call close() on the Connection.

The only difference is when the connection is closed but close() will be called.

If the connection will be actually closed depends on which DataSource is used, in general when using a connection pool the connection will be returned to the pool instead of actually closing the connection.

Answer 2:

Yes it does.

And if the connection was obtained from connection pool, it won’t actually close the connection, rather will send it back to the pool.

Answer 3:

No need to close the connection manually. Spring container itself to take of the operation. Kindly refer this spring url,

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html

Answer 4:

We can also close connection while using jdbcTemplete, in some cases it compulsory to close connection after execute query otherwise getting connection issue. for more details visit [Close connection in jdbc template][1] [1]: http://www.javaiq.in/2019/05/jdbctemplate.html

Link is: https://inneka.com/programming/spring/does-springs-jdbctemplate-close-the-connection-after-query-timeout/

Abdusoli
  • 661
  • 1
  • 8
  • 24