简体   繁体   中英

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());
    }
}

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
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM