How to use Spring Boot JDBC driver connection to connect the database

Last updated on May 30 2022
Amarjit Malik

Table of Contents

How to use Spring Boot JDBC driver connection to connect the database

Spring Boot provides a very good support to create a DataSource for Database. We need not write any extra code to create a DataSource in Spring Boot. Just adding the dependencies and doing the configuration details is enough to create a DataSource and connect the Database.

In this blog , we are going to use Spring Boot JDBC driver connection to connect the database.

First, we need to add the Spring Boot Starter JDBC dependency in our build configuration file.

Maven users can add the following dependencies in the pom.xml file.

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

Gradle users can add the following dependencies in the build.gradle file.

compile(‘org.springframework.boot:spring-boot-starter-jdbc’)

Connect to H2 database

To connect the H2 database, we need to add the H2 database dependency in our build configuration file.

For Maven users, add the below dependency in your pom.xml file.

<dependency>   <groupId>com.h2database</groupId>   <artifactId>h2</artifactId></dependency>

For Gradle users, add the below dependency in your build.gradle file.

compile(‘com.h2database:h2′)

We need to create the schema.sql file and data.sql file under the classpath src/main/resources directory to connect the H2 database.

The schema.sql file is given below.

CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25));

The data.sql file is given below.

INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,’Honey’);INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,’Almond’);

Connect MySQL

To connect the MySQL database, we need to add the MySQL dependency into our build configuration file.

For Maven users, add the following dependency in your pom.xml file.

<dependency>   <groupId>mysql</groupId>   <artifactId>mysql-connector-java</artifactId></dependency>

For Gradle users, add the following dependency in your build.gradle file.

compile(‘mysql:mysql-connector-java’)

Now, create database and tables in MySQL as shown −

Page 2 Image 1
mysql

For properties file users, add the following properties in the application.properties file.

spring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = truespring.datasource.username = rootspring.datasource.password = rootspring.datasource.testOnBorrow = truespring.datasource.testWhileIdle = truespring.datasource.timeBetweenEvictionRunsMillis = 60000spring.datasource.minEvictableIdleTimeMillis = 30000spring.datasource.validationQuery = SELECT 1spring.datasource.max-active = 15spring.datasource.max-idle = 10spring.datasource.max-wait = 8000

For YAML users, add the following properties in the application.yml file.

spring:   datasource:       driverClassName: com.mysql.jdbc.Driver      url: “jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true”      username: “root”      password: “root”      testOnBorrow: true      testWhileIdle: true      timeBetweenEvictionRunsMillis: 60000      minEvictableIdleTimeMillis: 30000      validationQuery: SELECT 1      max-active: 15      max-idle: 10      max-wait: 8000

Connect Redis

Redis is an open source database used to store the in-memory data structure. To connect the Redis database in Spring Boot application, we need to add the Redis dependency in our build configuration file.

Maven users should add the following dependency in your pom.xml file.

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

Gradle users should add the following dependency in your build.gradle file.

compile(‘org.springframework.boot:spring-boot-starter-data-redis’)

For Redis connection, we need to use RedisTemplate. For RedisTemplate we need to provide the JedisConnectionFactory details.

@BeanJedisConnectionFactory jedisConnectionFactory() {   JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();   jedisConFactory.setHostName(“localhost”);   jedisConFactory.setPort(6000);   jedisConFactory.setUsePool(true);   return jedisConFactory;}@Beanpublic RedisTemplate<String, Object> redisTemplate() {   RedisTemplate<String, Object> template = new RedisTemplate<>();   template.setConnectionFactory(jedisConnectionFactory());   template.setKeySerializer(new StringRedisSerializer());   template.setHashKeySerializer(new StringRedisSerializer());   template.setHashValueSerializer(new StringRedisSerializer());   template.setValueSerializer(new StringRedisSerializer());   return template;}

Now auto wire the RedisTemplate class and access the data from Redis database.

@Autowired RedisTemplate<String, Object> redis;Map<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”);

JDBCTemplate

To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file.

Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.

@AutowiredJdbcTemplate jdbcTemplate;Collection<Map<String, Object>> rows = jdbc.queryForList(“SELECT QUERY”);

The @Repository annotation should be added into the class file. The @Repository annotation is used to create database repository for your Spring Boot application.

@Repositorypublic class ProductServiceDAO {}

Multiple DataSource

We can keep ‘n’ number Datasources in a single Spring Boot application. The example given here shows how to create more than 1 data source in Spring Boot application. Now, add the two data source configuration details in the application properties file.

For properties file users, add the following properties into your application.properties file.

spring.dbProductService.driverClassName = com.mysql.jdbc.Driverspring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = truespring.dbProductService.username = rootspring.dbProductService.password = rootspring.dbProductService.testOnBorrow = truespring.dbProductService.testWhileIdle = truespring.dbProductService.timeBetweenEvictionRunsMillis = 60000spring.dbProductService.minEvictableIdleTimeMillis = 30000spring.dbProductService.validationQuery = SELECT 1spring.dbProductService.max-active = 15spring.dbProductService.max-idle = 10spring.dbProductService.max-wait = 8000 spring.dbUserService.driverClassName = com.mysql.jdbc.Driverspring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = truespring.dbUserService.username = rootspring.dbUserService.password = rootspring.dbUserService.testOnBorrow = truespring.dbUserService.testWhileIdle = truespring.dbUserService.timeBetweenEvictionRunsMillis = 60000spring.dbUserService.minEvictableIdleTimeMillis = 30000spring.dbUserService.validationQuery = SELECT 1spring.dbUserService.max-active = 15spring.dbUserService.max-idle = 10spring.dbUserService.max-wait = 8000

Yaml users should add the following properties in your application.yml file.

spring:   dbProductService:       driverClassName: com.mysql.jdbc.Driver      url: “jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true”      password: “root”      username: “root”      testOnBorrow: true      testWhileIdle: true      timeBetweenEvictionRunsMillis: 60000      minEvictableIdleTimeMillis: 30000      validationQuery: SELECT 1      max-active: 15      max-idle: 10      max-wait: 8000   dbUserService:       driverClassName: com.mysql.jdbc.Driver      url: “jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true”      password: “root”      username: “root”      testOnBorrow: true      testWhileIdle: true      timeBetweenEvictionRunsMillis: 60000      minEvictableIdleTimeMillis: 30000      validationQuery: SELECT 1          max-active: 15      max-idle: 10      max-wait: 8000

Now, create a Configuration class to create a DataSource and JdbcTemplate for multiple data sources.

import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.jdbc.core.JdbcTemplate; @Configurationpublic class DatabaseConfig {   @Bean(name = “dbProductService”)   @ConfigurationProperties(prefix = “spring.dbProductService”)   @Primary   public DataSource createProductServiceDataSource() {      return DataSourceBuilder.create().build();   }   @Bean(name = “dbUserService”)   @ConfigurationProperties(prefix = “spring.dbUserService”)   public DataSource createUserServiceDataSource() {      return DataSourceBuilder.create().build();   }   @Bean(name = “jdbcProductService”)   @Autowired   public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier(“dbProductService”) DataSource productServiceDS) {      return new JdbcTemplate(productServiceDS);   }   @Bean(name = “jdbcUserService”)   @Autowired   public JdbcTemplate createJdbcTemplate_UserService(@Qualifier(“dbUserService”) DataSource userServiceDS) {      return new JdbcTemplate(userServiceDS);   }}

Then, auto wire the JDBCTemplate object by using @Qualifier annotation.

@Qualifier(“jdbcProductService”)@AutowiredJdbcTemplate jdbcTemplate; @Qualifier(“jdbcUserService”)@AutowiredJdbcTemplate jdbcTemplate;

 

So, this brings us to the end of blog. This Tecklearn ‘How to use Spring Boot JDBC driver connection to connect the database’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Spring Boot and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

0 responses on "How to use Spring Boot JDBC driver connection to connect the database"

Leave a Message

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