How to Use Spring JdbcTemplate

By | June 10, 2018

This is how to use spring JdbcTemplate in spring boot application.

In this example i’m using :

  • Spring boot 2.0.2.RELEASE
  • Maven 3.5.3 for build tools
  • Java 1.8

How to Use Spring JdbcTemplate

First import spring jdbc library:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Second, create new java class for JdbcTemplate configuration like this:

@Component
public class JdbcConfig {

    @Value("${spring.datasource.driverClassName}")
    String driverClassName;

    @Value("${spring.datasource.url}")
    String url;

    @Value("${spring.datasource.username}")
    String username;

    @Value("${spring.datasource.password}")
    String password;

    @Bean
    public JdbcTemplate template(){
        HikariDataSource source = new HikariDataSource();
        source.setDriverClassName(driverClassName);
        source.setJdbcUrl(url);
        source.setUsername(username);
        source.setPassword(password);
        return new JdbcTemplate(source);
    }

}

Then you can use in your controller or service class like this:

@Autowired
private JdbcTemplate jdbc;
public Collection<Question> getQuestionByTopicId(Integer id){
    return jdbc.query(
            "select * from master_question",
            new Object[]{id},
            (rs, i) -> new Question(
                    rs.getInt("id"),
                    rs.getString("question")
            )
    );
}

How to Use Spring JdbcTemplate

That’s it.
If you have a question, please feel free to ask me. Thank you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *