Spring Boot JDBC

Spring Boot JDBC with features, project,starter project wizard,cli,application,annotations,dm,properties,actuator,thymeleaf view,jpa,jdbc etc

Spring Boot JDBC

Spring Boot JDBC

Spring Boot provides starter and libraries for connecting to our application with JDBC. Here, we are creating an application that connects with the Mysql database. It includes the following steps to create and setup JDBC with Spring Boot.

Create a database

  1. create database springbootdb  

Create a table in to mysql

  1. create table user(id int UNSIGNED primary key not null auto_increment, name varchar(100), email varchar(100));  

Creating a Spring Boot Pproject

Providing project name and other project related information.

Providing dependencies

After finishing, create following files in your project.

Configure database into application.properties file.

// application.properties

  1. spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb  
  2. spring.datasource.username=root  
  3. spring.datasource.password=mysql  
  4. spring.jpa.hibernate.ddl-auto=create-drop  

// SpringBootJdbcApplication.java

  1. package com.tpoint;  
  2. import org.springframework.boot.SpringApplication;  
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  4. @SpringBootApplication  
  5. public class SpringBootJdbcApplication {  
  6.     public static void main(String[] args) {  
  7.         SpringApplication.run(SpringBootJdbcApplication.class, args);  
  8.     }  
  9. }  

Creating a controller to handle HTTP requests.

// SpringBootJdbcController.java

  1. package com.tpoint;  
  2. import org.springframework.web.bind.annotation.RequestMapping;  
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.jdbc.core.JdbcTemplate;  
  5. import org.springframework.web.bind.annotation.RestController;  
  6. @RestController  
  7. public class SpringBootJdbcController {  
  8.     @Autowired  
  9.     JdbcTemplate jdbc;    
  10.     @RequestMapping("/insert")  
  11.     public String index(){  
  12.         jdbc.execute("insert into user(name,email)values('javatpoint','java@javatpoint.com')");  
  13.         return"data inserted Successfully";  
  14.     }  
  15.  

Run the application

Run SpringBootJdbcApplication.java file as Java application.

Now, open browser and follow the following URL.

It says data has inserted successfully. let's confirm it by checking mysql table.

Well, our application is working fine. Now, we can perform other database operations as well.