title: Spring boot: Database connection not closing properly
body: <p>I'm executing queries periodically (by a scheduler) using my Spring Boot application </p>
  
  <p><strong>application.properties</strong></p>
  
  <pre><code>src_mssqlserver_url=jdbc:sqlserver://192.168.0.1;databaseName=Test;
  src_mssqlserver_username=tester
  src_mssqlserver_password=tester1
  src_mssqlserver_driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
  </code></pre>
  
  <p><strong>Datasource and JdbcTemplate Bean</strong></p>
  
  <pre><code>@Primary
      @Bean(name = "src_mssqlserver")
      @ConfigurationProperties(prefix = "spring.ds_mssqlserver")
      public DataSource srcDataSource() {
  
          DriverManagerDataSource dataSource = new DriverManagerDataSource();
          dataSource.setDriverClassName(env.getProperty("src_mssqlserver_driverClassName"));
          dataSource.setUrl(env.getProperty("src_mssqlserver_url"));
          dataSource.setUsername(env.getProperty("src_mssqlserver_username"));
          dataSource.setPassword(env.getProperty("src_mssqlserver_password"));
          return dataSource;
      }
  
      @Bean(name = "srcJdbcTemplate")
      public JdbcTemplate srcJdbcTemplate(@Qualifier("src_mssqlserver") DataSource dsSrcSqlServer) {
          return new JdbcTemplate(dsSrcSqlServer);
      }
  </code></pre>
  
  <p><strong>Usage: This method is called from a scheduler with list of items to process (normally 1000 records), this process runs in an hour once.</strong></p>
  
  <pre><code>@Autowired
  @Qualifier("srcJdbcTemplate")
  private JdbcTemplate srcJdbcTemplate;
  
  public void batchInsertUsers(final List&lt;User&gt; users) {
          String queryInsert = "INSERT INTO [User] ([Name]"
                  + "     , [Created_Date]"
                  + "     , [Notes])"
                  + " VALUES (?, SYSDATETIMEOFFSET(), ?)";
  
          srcJdbcTemplate.batchUpdate(queryInsert, new BatchPreparedStatementSetter() {
              @Override
              public void setValues(PreparedStatement ps, int i) throws SQLException {
                  User user = users.get(i);
  
                  ps.setString(1, user.getName());
                  ps.setString(2, user.getNotes());
              }
  
              @Override
              public int getBatchSize() {
                  return sites.size();
              }
          });
  </code></pre>
  
  <p>I'm getting warnings from database administrator that my code keeping too much connections open. Please share some standard and workable way to handle such situation.</p>
  
  <p>Thanks.</p>