2

I'm trying to set up pooling with SQLServerDataSource if i understand this answer https://stackoverflow.com/a/25573035/1262568

public DataSource dataSource() {
    DataSourceBuilder factory = DataSourceBuilder
            .create(this.properties.getClassLoader())
            .driverClassName(this.properties.getDriverClassName())
            .url(this.properties.getUrl())
            .username(this.properties.getUsername())
            .password(this.properties.getPassword());
    return factory.build();
}

Geting connection from a DataSource created in that way will return pooled connection using one of the available connection pools. But what if instead DataSourceBuilder i want to use SQLServerDataSource Will it also automatically use one of the available connection pool?

public DataSource dataSource() {
SQLServerDataSource sqlServerDataSource = new SQLServerDataSource();
        sqlServerDataSource.setUser(UserName);
        sqlServerDataSource.setPassword(Password);
        sqlServerDataSource.setURL(Url);
        return sqlServerDataSource;
}
whd
  • 1,819
  • 1
  • 21
  • 52

1 Answers1

1

Will it also automatically use one of the available connection pool?

No it won't. SQLServerDataSource is a SQL Server (driver) specific class, whereas DataSourceBuilder is a Spring class. Only the latter knows about Spring and its configuration and its configured connection pool.

Is there a reason you'd need to use SQLServerDataSource?

To access the native connection even from the pool, use

SQLServerConnection conn = connection.unwrap(SQLServerConnection.class);

just remember to call close() on connection and not conn, so the connection can be returned to the pool.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • I don't know if there is a reason. It's a legacy code, will try to change it. – whd Sep 11 '19 at 13:23
  • 2
    With JDBC you almost always use only the interfaces of the specification (`Connection`, `DataSource`, `ResultSet` etc.). Dipping into the actual driver classes is only necessary when you're attempting to do something complicated that cannot be achieved through regular JDBC (i.e. something very database specific). – Kayaman Sep 11 '19 at 13:24
  • because bulkinsert is used connection must be optained from `SQLServerDataSource` – whd Sep 11 '19 at 15:51
  • 2
    In that case you should be able to use `connection.unwrap(SQLConnection.class)` (or whatever is the implementing class) to get the native connection where you need it. – Kayaman Sep 11 '19 at 15:55