一、快速创建项目
1. 创建项目
2. 项目细节
3. 勾选项目依赖
- Web模块中选择Spring web依赖
- SQL模块中选以下两个依赖
- JDBC API 会导入
spring-boot-starter-jdbc
依赖 - MySql Driver 会导入
mysql-connector-java
依赖 - (这个不选)Spring Data JDBC 会导入
spring-boot-starter-data-jdbc
依赖
- JDBC API 会导入
4. 项目结构
(controller包 是下面要写的测试类)
二、数据库结构
三、pom.xml文件依赖
对应创建项目时勾选的项目依赖包:
spring-boot-starter-jdbc
:SQL模块JDBC APImysql-connector-java
:SQL模块 MySql Driverspring-boot-starter-web
:Web模块的 Spring Webspring-boot-starter-test
(默认带的依赖)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.feng.jdbc</groupId>
<artifactId>springboot_jdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_jdbc</name>
<description>springboot_jdbc</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
四、application.yml配置文件
项目中如果加入了有关jdbc的依赖包,就必须要配置数据源信息,否则会报错,如下
加如下配置即可
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://IP:3306/feng?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
则启动OK
五、controller 测试
1. 测试类
package com.feng.springboot_jdbc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
// //我们以后会经常看见xxxxTemplate,这个是spring boot已经配置好的模板@bean,拿来即用
@Autowired
private JdbcTemplate jdbcTemplate;
@GetMapping("/test")
public String getStr() {
return "hello world";
}
@GetMapping("/add")
public String getUser() {
String sql = "INSERT INTO user_data(user_id , user_name) VALUES (2, 'fanli')";
int update = jdbcTemplate.update(sql);
return "ok:" + update;
}
}
2. 测试请求结果
- 测试接口:
http://localhost:8080/test
- 新增请求:
http://localhost:8080/add