Spring Boot 入门:如何连接 MySQL 数据库
大家好呀!之前我们写的接口都是用 “模拟数据库”(比如 List 存数据),但实际开发中,数据肯定要存在真实的数据库里 —— 今天这篇就带大家用 SQL 脚本创建数据库表、YAML 配置连接信息,最后用 ApiFox 测试接口,全程贴合企业开发规范,零基础也能一步到位!
全程分 5 步走,每一步都有可直接复制的代码和操作截图级说明,跟着做就能成功~
一、准备工作:装好这 3 个工具
在开始之前,先准备好 MySQL 数据库、可视化工具和接口测试工具,确保后续操作顺畅:
1. 安装 MySQL 数据库(以 MySQL 8.0 为例)
- 下载:去 MySQL 官网下载 MySQL Installer(Windows)或 DMG 包(Mac),选 8.0 版本(稳定且常用);
- 安装:
- Windows:双击安装包,选 “Developer Default”,一路下一步,设置 root 密码(比如
123456,记牢!); - Mac:双击 DMG 包,按提示安装,同样设置 root 密码;
- 验证:打开 “命令提示符”(Windows)或 “终端”(Mac),输入
mysql -u root -p,输密码后若显示mysql>提示符,说明安装成功。
2. 安装 MySQL 可视化工具(DataGrip)
DataGrip 是 JetBrains 旗下专业数据库工具,支持 SQL 脚本执行和表管理,操作高效:
- 安装:去 JetBrains 官网下载对应系统版本,默认下一步安装;
- 连接 MySQL:
- 打开 DataGrip,点击左侧 “Database” 面板的 “+”→“Data Source”→“MySQL”;
- 输入 Host(
localhost)、Port(3306)、User(root)、Password(你的 MySQL 密码); - 点击 “Test Connection”,提示 “Connection successful” 即连接成功,点 “OK” 保存。
3. 安装接口测试工具(ApiFox)
ApiFox 比 Postman 更贴合国内开发者习惯,支持接口调试、文档生成,免费好用:
- 安装:去 ApiFox 官网下载安装包,默认下一步安装;
- 初始化:打开后注册账号,新建 “Spring Boot 数据库测试” 项目(后续用来测试接口)。
二、第一步:用 SQL 脚本创建数据库、表和测试数据
企业开发中,创建数据库表通常用 SQL 脚本(方便版本控制和团队共享),这里直接提供可复制的完整脚本,不用手动点界面创建!
1. 执行 SQL 脚本的步骤
- 打开 DataGrip,右键点击已连接的 MySQL 实例→“New”→“Query Console”,打开 SQL 控制台;
- 复制下面的完整 SQL 脚本,粘贴到控制台;
- 点击控制台左上角的 “执行” 按钮(绿色三角),等待执行完成(下方日志无红色报错即成功)。
2. 完整 SQL 脚本(复制即用)
-- 1. 创建数据库(如果不存在)
create database if not exists springboot_demo character set utf8mb4 collate utf8mb4_general_ci;
-- 2. 使用创建好的数据库
use springboot_demo;
-- 3. 创建用户表(user)
drop table if exists user;
create table user (
id int(11) not null auto_increment comment '用户ID(自增)',
name varchar(50) not null comment '用户名',
age int(3) default null comment '用户年龄',
phone varchar(20) default null comment '用户手机号',
primary key (id)
) default charset = utf8mb4 comment ='用户表';
-- 4. 创建商品表(product)
drop table if exists product;
create table product
(
product_id int(11) not null auto_increment comment '商品ID(自增)',
product_name varchar(100) not null comment '商品名称',
price double not null comment '商品价格',
stock int(11) not null comment '商品库存',
primary key (product_id)
) default charset = utf8mb4 comment ='商品表';
-- 5. 插入用户测试数据
insert into user (name, age, phone) values ('小明', 20, '13800138000');
insert into user (name, age, phone) values ('小红', 19, '13900139000');
-- 6. 插入商品测试数据
insert into product (product_name, price, stock) values ('华为手机', 3999.0, 100);
insert into product (product_name, price, stock) values ('苹果平板', 5999.0, 50);
insert into product (product_name, price, stock) values ('小米耳机', 299.0, 200);
insert into product (product_name, price, stock) values ('OPPO手机', 2999.0, 80);
3. 验证脚本执行结果
- 执行完成后,刷新 DataGrip 左侧 “Database” 面板的 “springboot_demo” 数据库;
- 展开 “Tables”,能看到
user和product两张表; - 右键点击
user表→“Open Table”,能看到 2 条测试用户数据;同理,product表有 4 条测试商品数据,说明脚本执行成功。
三、第二步:项目添加数据库依赖
回到 IDEA,给之前的first-springboot-project项目添加 MySQL 和 MyBatis 依赖,让项目能操作数据库:
1. 打开 pom.xml 文件
在左侧项目结构中,找到pom.xml(Maven 依赖配置文件),双击打开。
2. 添加依赖代码
在<dependencies>标签内粘贴以下依赖(复制即用):
<!-- 1. MySQL驱动依赖:让Spring Boot识别MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version> <!-- 与MySQL 8.0匹配 -->
<scope>runtime</scope>
</dependency>
<!-- 2. MyBatis依赖:简化数据库操作(需配合XML写SQL) -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
3. 刷新依赖
点击 IDEA 右上角的 “Load Maven Changes”(刷新图标),等待 Maven 下载依赖(右下角进度条走完无报错即可)。
四、第三步: 配置数据库和 MyBatis
1. 粘贴 YAML 配置代码
# 1. 服务器配置(可选,保持8080端口)
server:
port: 8080
# 2. 数据库连接配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_demo?characterEncoding=utf8
username: root
password: 12345678 # 替换成你的MySQL密码
#3.定义mapper.xml位置
mybatis:
mapper-locations: classpath:mapper/**/*.xml
# 4. 日志配置(打印SQL,方便调试)
logging:
level:
com.example.firstspringbootproject.mapper: debug
3. YAML 配置说明
- 缩进注意:YAML 用空格缩进(不能用 Tab),
server、spring、mybatis是同级节点,子节点需缩进 2 个空格; - 数据库配置:
springboot_demo是我们用 SQL 创建的数据库名,password必须替换成你的 MySQL 密码; - 下划线转驼峰:开启后不用在 XML 中写
AS别名(如product_id自动对应实体类productId),减少代码量。
五、第四步:编写代码,实现数据库操作(核心步骤)
用 MyBatis 操作数据库,需写 3 部分代码:Mapper 接口(定义方法)、Mapper XML(写 SQL)、Service+Controller(调用逻辑),每部分都有可复制的代码:
1. 第一步:创建 Mapper 接口(定义数据库操作方法)
Mapper 接口是 MyBatis 的 “入口”,定义查询、新增等方法,不用写实现类(MyBatis 自动生成)。
(1)创建 Mapper 包和接口
- 右键点击
com.example.firstspringbootproject包→“New”→“Package”,输入包名mapper; - 在
mapper包下创建UserMapper接口:
package com.example.firstspringbootproject.mapper;
import com.example.firstspringbootproject.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
// @Mapper:告诉Spring Boot这是MyBatis的Mapper接口
@Mapper
public interface UserMapper {
// 1. 根据ID查询用户
User selectById(Integer id);
// 2. 新增用户
int insert(User user);
// 3. 查询所有用户
List<User> selectAll();
}
- 在
mapper包下创建ProductMapper接口:
package com.example.firstspringbootproject.mapper;
import com.example.firstspringbootproject.entity.Product;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ProductMapper {
// 1. 根据ID查询商品
Product selectById(Integer productId);
// 2. 根据名称模糊查询商品
List<Product> selectByName(String name);
}
2. 第二步:创建 Mapper XML(写 SQL 语句)
Mapper XML 文件用来写具体的 SQL 语句,和 Mapper 接口一一对应:
(1)创建 Mapper XML 目录
在src/main/resources目录下,右键点击→“New”→“Directory”,输入目录名mapper。
(2)创建 UserMapper.xml
在mapper目录下新建UserMapper.xml,粘贴代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace必须和Mapper接口全路径一致 -->
<mapper namespace="com.example.firstspringbootproject.mapper.UserMapper">
<!--
第一步:定义一个 resultMap
- id: 这个 resultMap 的唯一标识,可以自由命名,通常以 "类名+ResultMap" 命名
- type: 映射的目标 Java 实体类的全路径
-->
<resultMap id="UserResultMap" type="com.example.firstspringbootproject.entity.User">
<!--
<id> 用于映射主键字段
- property: Java 对象中的属性名
- column: 数据库表中的字段名
-->
<id property="id" column="id"/>
<!--
<result> 用于映射普通字段
- property: Java 对象中的属性名
- column: 数据库表中的字段名
-->
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="phone" column="phone"/>
</resultMap>
<!--
第二步:在 select 语句中引用定义好的 resultMap
- resultMap: 值为上面定义的 resultMap 的 id
-->
<!-- 1. 根据ID查询用户 -->
<select id="selectById" resultMap="UserResultMap">
SELECT id, name, age, phone FROM user WHERE id = #{id}
</select>
<!-- 2. 新增用户:useGeneratedKeys开启自增ID回显 -->
<insert id="insert" useGeneratedKeys="true"
keyProperty="id">
INSERT INTO user (name, age, phone) VALUES (#{name}, #{age}, #{phone})
</insert>
<!-- 3. 查询所有用户 -->
<select id="selectAll" resultMap="UserResultMap">
SELECT id, name, age, phone FROM user
</select>
</mapper>
(3)创建 ProductMapper.xml
在mapper目录下新建ProductMapper.xml,粘贴代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.firstspringbootproject.mapper.ProductMapper">
<!--
第一步:定义一个 resultMap
- id: 这个 resultMap 的唯一标识
- type: 映射的目标 Java 实体类
-->
<resultMap id="ProductResultMap" type="com.example.firstspringbootproject.entity.Product">
<!--
<id> 用于映射主键字段
- property: Java 对象中的属性名 (e.g., productId)
- column: 数据库表中的字段名 (e.g., product_id)
-->
<id property="productId" column="product_id"/>
<!--
<result> 用于映射普通字段
-->
<result property="productName" column="product_name"/>
<result property="price" column="price"/>
<result property="stock" column="stock"/>
</resultMap>
<!--
第二步:在 select 语句中引用定义好的 resultMap
-->
<!-- 1. 根据ID查询商品 -->
<select id="selectById" resultMap="ProductResultMap">
SELECT product_id, product_name, price, stock FROM product WHERE product_id = #{productId}
</select>
<!-- 2. 根据名称模糊查询商品 -->
<select id="selectByName" resultMap="ProductResultMap">
SELECT product_id, product_name, price, stock FROM product
WHERE product_name LIKE CONCAT('%', #{name}, '%')
</select>
</mapper>
3. 第三步:创建 Service 层(封装业务逻辑)
Service 层隔离 Controller 和 Mapper,处理业务逻辑(如判断新增是否成功),让代码更规范:
(1)创建 Service 接口
- 右键点击
com.example.firstspringbootproject包→“New”→“Package”,输入包名service; - 在
service包下创建UserService接口:
package com.example.firstspringbootproject.service;
import com.example.firstspringbootproject.entity.User;
import java.util.List;
public interface UserService {
User getUserById(Integer id); // 根据ID查用户
boolean addUser(User user); // 新增用户
List<User> getAllUsers(); // 查所有用户
}
- 在
service包下创建ProductService接口:
package com.example.firstspringbootproject.service;
import com.example.firstspringbootproject.entity.Product;
import java.util.List;
public interface ProductService {
Product getProductById(Integer productId); // 根据ID查商品
List<Product> searchProductByName(String name); // 模糊查商品
}
(2)创建 Service 实现类
- 在
service包下新建impl包; - 在
impl包下创建UserServiceImpl类:
package com.example.firstspringbootproject.service.impl;
import com.example.firstspringbootproject.entity.User;
import com.example.firstspringbootproject.mapper.UserMapper;
import com.example.firstspringbootproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
// @Service:标记这是Service层实现类,Spring自动管理
@Service
public class UserServiceImpl implements UserService {
// 注入UserMapper(Spring自动创建实例)
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.selectById(id); // 调用Mapper方法
}
@Override
public boolean addUser(User user) {
int rows = userMapper.insert(user); // 新增返回影响行数
return rows > 0; // 行数>0表示新增成功
}
@Override
public List<User> getAllUsers() {
return userMapper.selectAll();
}
}
- 在
impl包下创建ProductServiceImpl类:
package com.example.firstspringbootproject.service.impl;
import com.example.firstspringbootproject.entity.Product;
import com.example.firstspringbootproject.mapper.ProductMapper;
import com.example.firstspringbootproject.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductMapper productMapper;
@Override
public Product getProductById(Integer productId) {
return productMapper.selectById(productId);
}
@Override
public List<Product> searchProductByName(String name) {
return productMapper.selectByName(name);
}
}
4. 第四步:创建 Controller(接口入口)
Controller 层提供接口地址,接收请求并调用 Service,返回 JSON 数据:
在com.example.firstspringbootproject.controller包下创建DbController类(专门处理数据库相关接口):
package com.example.firstspringbootproject.controller;
import com.example.firstspringbootproject.entity.Product;
import com.example.firstspringbootproject.entity.User;
import com.example.firstspringbootproject.service.ProductService;
import com.example.firstspringbootproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController // 自动返回JSON
@RequestMapping("/api") // 接口统一前缀(如/api/user/1)
public class DbController {
@Autowired
private UserService userService;
@Autowired
private ProductService productService;
// 1. 根据用户ID查询(路径传参)
@GetMapping("/user/{userId}")
public User getUser(@PathVariable Integer userId) {
return userService.getUserById(userId);
}
// 2. 新增用户(请求体传参)
@PostMapping("/user")
public String addUser(@RequestBody User user) {
boolean success = userService.addUser(user);
return success ? "新增成功!用户ID:" + user.getId() : "新增失败!";
}
// 3. 查询所有用户
@GetMapping("/user/all")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
// 4. 根据商品ID查询
@GetMapping("/product/{productId}")
public Product getProduct(@PathVariable Integer productId) {
return productService.getProductById(productId);
}
// 5. 模糊搜索商品(问号传参)
@GetMapping("/product/search")
public List<Product> searchProduct(@RequestParam(required = false, defaultValue = "") String name) {
return productService.searchProductByName(name);
}
}
六、第五步:用 ApiFox 测试接口(验证真实数据操作)
代码写完后,用 ApiFox 测试接口,看是否能正确操作 MySQL 数据库里的真实数据:
1. 运行 Spring Boot 项目
- 找到
FirstSpringbootProjectApplication启动类,点击绿色三角运行; - 控制台显示 “Started FirstSpringbootProjectApplication in xxx seconds” 且无红色报错,说明项目启动成功;
- 查看控制台日志,能看到 MyBatis 打印的 SQL 语句(如后续调用接口时,会显示
SELECT id, name, age, phone FROM user WHERE id = ?)。
2. 用 ApiFox 测试 5 个接口
打开 ApiFox,在之前新建的 “Spring Boot 数据库测试” 项目中,按以下步骤测试每个接口:
测试 1:根据用户 ID 查询(/api/user/{userId})
- 点击左侧 “+”→“HTTP 请求”,输入请求名称 “根据用户 ID 查用户”;
- 方法选 “GET”,URL 输入
http://localhost:8080/api/user/1(查询 ID=1 的用户); - 点击 “发送”,查看 “响应体”:
- 返回
{"id":1,"name":"小明","age":20,"phone":"13800138000"},和数据库中数据一致,测试成功!
测试 2:新增用户(/api/user)
- 新建请求,名称 “新增用户”,方法选 “POST”,URL 输入
http://localhost:8080/api/user; - 点击 “请求体”→“JSON”,输入:
{
"name": "小李",
"age": 22,
"phone": "13700137000"
}
- 点击 “发送”,响应体返回 “新增成功!用户 ID:3”;
- 验证数据库:在 DataGrip 中打开
user表,能看到新增的 “小李” 记录(ID=3),测试成功!
测试 3:查询所有用户(/api/user/all)
- 新建 GET 请求,URL
http://localhost:8080/api/user/all; - 发送后,响应体返回 3 条用户数据(含刚新增的小李),测试成功!
测试 4:根据商品 ID 查询(/api/product/{productId})
- 新建 GET 请求,URL
http://localhost:8080/api/product/1(查询 ID=1 的商品); - 发送后,返回
{"productId":1,"productName":"华为手机","price":3999.0,"stock":100},和数据库一致,测试成功!
测试 5:模糊搜索商品(/api/product/search)
- 新建 GET 请求,URL
http://localhost:8080/api/product/search?name=手机(搜索名称含 “手机” 的商品); - 发送后,响应体返回 2 条数据(华为手机、OPPO 手机),和数据库一致,测试成功!
七、常见问题:避坑指南
1. 启动项目时报 “Access denied for user 'root'@'localhost' (using password: YES)”?
- 原因:MySQL 密码错误;
- 解决方案:检查
application.yml中spring.datasource.password是否和你的 MySQL 密码一致。
2. 报 “Could not find resource mapper/UserMapper.xml”?
- 原因:MyBatis 找不到 Mapper XML 文件,路径配置错误;
- 解决方案:确认
application.yaml中mybatis.mapper-locations是classpath:mapper/**/*.xml,且 XML 文件确实在src/main/resources/mapper目录下。
3. 接口返回数据中,中文乱码?
- 原因:数据库字符集不是 utf8mb4;
- 解决方案:重新执行第二步中的 SQL 脚本(脚本开头已设置
CHARACTER SET utf8mb4),或在 DataGrip 中右键点击springboot_demo数据库→“Properties”,将字符集改为utf8mb4。
4. 报 “Invalid bound statement (not found): com.example.firstspringbootproject.mapper.UserMapper.selectById”?
- 原因:Mapper XML 的
namespace和 Mapper 接口全路径不一致; - 解决方案:确认 XML 中
namespace的值(如com.example.firstspringbootproject.mapper.UserMapper)和接口的包路径、类名完全一致。
八、总结:从脚本到测试,全程贴合企业开发
今天我们完成了从 “模拟数据” 到 “真实数据库” 的跨越,学会了:
- 用 SQL 脚本批量创建数据库、表和测试数据,高效且便于团队协作;
- 用 YAML 格式配置 Spring Boot,结构更清晰,减少配置冗余;
- 用 MyBatis 写 Mapper 接口和 XML,灵活控制 SQL 语句;
- 用 ApiFox 测试接口,快速验证数据库操作结果。
现在你的接口已经完全符合企业开发标准 —— 数据存在 MySQL 中,代码分层清晰,测试工具专业。接下来可以自己拓展功能,比如 “修改商品库存”“删除用户”,只需在 Mapper 中新增方法和 SQL,在 Service 和 Controller 中调用即可。
下一篇文章,我会教大家 “全局异常处理” 和 “统一返回格式”(比如查询不到数据时,返回{"code":404,"msg":"数据不存在","data":null},而不是直接返回 null),让接口更健壮、更易维护!感兴趣的小伙伴点个关注,下次更新不迷路~
如果操作中遇到问题,欢迎在评论区留言,我会一一回复~