JDBC in Spring Boot applications

You can use Spring Data JDBC to implement JDBC based repositories. It enables applications to access Db2® and other data sources from your Spring Boot application.

Spring Data JDBC is a Spring module that is conceptually similar to JPA, it enhances JDBC support to access databases through Java™ objects. For more information, see Spring Data JDBC - Reference Documentation.

To use JDBC in your Spring Boot application, add a JDBC artifact to your dependencies in your Spring Boot application to make the necessary Java libraries available. For example, in Gradle,
implementation "org.springframework.boot:spring-boot-starter-data-jdbc"
Or in Maven,
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

To use JDBC in a Spring Boot application, you can define a Liberty dataSource in the server.xml, identically to a Java EE application. The data source that is defined in server.xml can be looked up by JNDI by the jndiName attribute in the dataSource element. Spring Boot can use a javax.sql.DataSource to construct an instance of org.springframework.jdbc.core.JdbcTemplate. The DataSource object can be provided through the following methods.

  1. A JNDI lookup of the data source in an org.springframework.context.annotation.Bean annotated method and returning the data source. For example,
    @Bean
    public DataSource getDataSource()
    {
        String jndiName = "jdbc/myDataSource";
        JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    
        return dataSourceLookup.getDataSource(jndiName);
    }
  2. Naming the data source in the spring.datasource.jndi-name in the Spring application properties. Spring Boot creates a JdbcTemplate that uses the data source that is named in application.properties.
Note: In option 2, it is also possible to configure all the data source attributes necessary to connect a Spring application to the data source from within the application.properties file. The attributes are all defined in Common application properties in the Spring Boot documentation. However, this ties the application directly the data source, looking up a data source in JNDI is a more flexible approach.