DEV Community

Mac
Mac

Posted on

Spring Boot : JDBCTemplate

Example of how to setup Spring Boot with JDBCTeamplate

  • pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.12</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <scope>provided</scope>
</dependency>

spring-boot-starter-jdbc and JDBC Driver, in this case postgresql is mandatory.

  • application.properties
spring.datasource.url=jdbc:postgresql://localhost/{DBNAME}
spring.datasource.username={USERNAME}
spring.datasource.password={PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

We often don't need spring.datasource.driver-class-name because Spring can figured it out from url.

  • App.java
@Slf4j
@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main( String[] args ) {
        SpringApplication springApplication = new SpringApplication(App.class);
        springApplication.setWebApplicationType(WebApplicationType.NONE);
        springApplication.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("Count total row = {}", 
            jdbcTemplate.queryForObject("SELECT COUNT(id) FROM customer", Integer.class));
    }
}

JdbcTemplate is auto configured in Spring. We can Autowired it directly into any Spring bean class.

Top comments (0)