In this post, we will go through the configuration to setup Spring Boot with MySQL access and operations. In order to make the connection, we will use JDBC .
Intro
JDBC stands for Java DataBase Connectivity, and it is a Java API for implementing SQL queries. The basic JDBC configuration file looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Class.forName("数据库驱动的完整类名" ); Connection conn = DriverManager.getConnection("数据库地址" ,"用户名" ,"密码" ); Statement stmt=conn.createStatement(); stmt.executeUpdate("SQL语句" ); ResultSet rs = stmt.executeQuery("查询记录的SQL语句" ); while (rs.next()){ } rs.close(); stmt.close(); conn.close();
So now we will use a demo, and set it up step by step.
Config
Note: The configuration below is based on Spring Boot Hello World Demo with web starter
only.
Initialize DB in MySQL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 DROP DATABASE demo_springboot;CREATE DATABASE demo_springboot;USE demo_springboot; DROP TABLE IF EXISTS user ;CREATE TABLE user ( id INT (11 ) NOT NULL AUTO_INCREMENT, name VARCHAR (100 ) NOT NULL , password VARCHAR (100 ) NOT NULL , PRIMARY KEY (id) ) ENGINE= INNODB AUTO_INCREMENT= 1 DEFAULT CHARSET= utf8;
Connect Spring Boot to MySQL Add dependencies in pom.xml
:
1 2 3 4 5 6 7 8 9 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-jdbc</artifactId > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > </dependency >
Add Configurations to resources/application.properties
(use cj.jdbc
):
1 2 3 4 5 # 数据源基本配置 spring.datasource.url=jdbc:mysql://localhost:3306/demo_springboot?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=
Check the following dependencies in pom.xml
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > <exclusions > <exclusion > <groupId > junit</groupId > <artifactId > junit</artifactId > </exclusion > </exclusions > </dependency > <dependency > <groupId > org.junit.jupiter</groupId > <artifactId > junit-jupiter-api</artifactId > <version > 5.3.2</version > <scope > test</scope > </dependency > <dependency > <groupId > org.junit.jupiter</groupId > <artifactId > junit-jupiter-engine</artifactId > <version > 5.3.2</version > <scope > test</scope > </dependency >
And the following plugins:
1 2 3 4 5 6 7 8 9 10 11 12 13 <build > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > </plugin > <plugin > <artifactId > maven-surefire-plugin</artifactId > <version > 2.22.0</version > </plugin > </plugins > </build >
Test Connection (DemoApplicationTests
under test
folder):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package merikanto.demo;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;@SpringBootTest class DemoApplicationTests { @Autowired private DataSource dataSource; @Test public void datasourceTest () throws SQLException { Connection connection = dataSource.getConnection(); System.out.println(connection != null ); connection.close(); } }
Run Maven with the test class, and the connection is successful if it returns true
.
MySQL Operations via Spring Boot Add JdbcController
class to main
. Then we will do Create
and Read
from CRUD.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package merikanto.demo.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;import java.util.Map;@RestController public class JdbcController { @Autowired JdbcTemplate jdbcTemplate; @GetMapping("/users/queryAll") public List<Map<String, Object>> queryAll() { List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from user" ); return list; } @GetMapping("/users/insert") public Object insert (String name, String password) { if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false ; } jdbcTemplate.execute("insert into user(`name`,`password`) value (\"" + name + "\",\"" + password + "\")" ); return true ; } }
Then we try it in the browser, we shall see that the newly added records are fetched via queryAll
.
1 2 3 /users/insert?name=merikanto&password=123 /users/queryAll
And that is the basics for Spring Boot’s Database connection.
P. S. Hello Controller 1 2 3 4 5 6 7 8 9 10 11 12 13 package merikanto.demo;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.bind.annotation.RequestMapping;@RestController public class HelloController { @RequestMapping("/") public String index () { return "Hello World!" ; } }