javaspringspring-bootdatasource

Spring Boot DataSourceBuilder with HikariDataSource throws error


I am trying to learn different ways of creating DataSource. In this example https://github.com/ivoronline/springboot_db_datasource_create_DataSourceBuilder I have used DriverManagerDataSource.class to successfully create Datasource as shown below

application.properties

# ORACLE DB
my.spring.datasource.url      = jdbc:oracle:thin:@localhost:1522/orcl
my.spring.datasource.username = TEST
my.spring.datasource.password = LETMEIN

MyDatabaseConfig

@Configuration
public class MyDatabaseConfig {

  //=========================================================================================================
  // DATA SOURCE
  //=========================================================================================================
  @Bean
  @ConfigurationProperties("my.spring.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().type(DriverManagerDataSource.class).build();
  }

}

But when I try to replace DriverManagerDataSource.class with HikariDataSource.class I get error. I am confused because in this other https://github.com/ivoronline/springboot_db_datasource_SaveSameEntityToDifferetnSchema more complicated project this was working.

Error

Unable to determine Dialect without JDBC metadata (please set 'jakarta.persistence.jdbc.url' for common cases or 'hibernate.dialect' when a custom Dialect implementation must be provided) 

Also did I understand correctly that DriverManagerDataSource isn't using Connection Pool and that Spring Boot by default uses HikariDataSource with connection pool behind it? So this approach would be manually doing what Spring Boot does automatically?


Solution

  • The way you are creating the datasource is, slightly, wrong. First you should create a bean for type DataSourceProperties use that to bind the properties for my.spring.datasource to.

    Next use that bean to create the DataSource.

    @Bean
    @ConfigurationProperties("my.spring.datasource")
    public DataSourceProperties myDataSourceProperties() {
      return new DataSourceProperties();
    }
    
    @Bean
    @ConfigurationProperties("my.spring.datasource.hikari")
    public DataSource myDataSource(DataSourceProperties myDataSourceProperties) {
      return myDataSourceProperties.initializeDataSourceBuilder().build();
    }
    

    What is the difference you probably ask.

    Your solution will bind the properties to the resulting DataSource which is pretty vendor specific on how to do properties. Whereas this solution uses more common names and has some logic to adapt to well known connection pool solution (like Hikari, Tomcat, Commons DBCP etc.). The specific my.spring.datasource.hikari is then bound to the resulting datasource and contains vendor specific properties.