Search code examples
javaspring-data-jdbc

Do I need to configure the beans in the example below for my Spring Data JDBC project?


Do I need to configure the beans in the example below for my Spring Data JDBC project?

Even without those beans, I was able to have my repository queries working correctly.

As I understand, NamedParameterJdbcOperations is used only internally to submit SQL statements to the database and that developers don't use it directly.

Would like to get more clarifications on this.

@SpringBootApplication
@EnableJdbcRepositories
public class SpringDataJdbcApplication extends AbstractJdbcConfiguration
{
    public static void main(String[] args) 
    {
        SpringApplication.run(SpringDataJdbcApplication.class, args);
    }
    
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() 
    {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        return dataSourceBuilder.build();
    }
    
    @Bean
    NamedParameterJdbcOperations namedParameterJdbcOperations(DataSource dataSource) 
    { 
        return new NamedParameterJdbcTemplate(dataSource);
    }

    @Bean
    PlatformTransactionManager transactionManager() 
    { 
        return new DataSourceTransactionManager(dataSource());
    }
}

Solution

  • If you include org.springframework.boot:spring-boot-starter-data-jdbc in dependencies in Maven or Gradle,By "Convention over configuration" paradigm, you shouldn't need to create any bean at all include the dataSource bean. Just main method is enough. Those necessary beans will be created automatically.

    @SpringBootApplication
    public class SpringDataJdbcApplication
    {
        public static void main(String[] args) 
        {
            SpringApplication.run(SpringDataJdbcApplication.class, args);
        }
        
    }
    

    and inside application.yml

    ...
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://dbhost/db
        username: xxx
        password: xxx
        max-active: 3
    ...