在Springboot项目中引入Mybatis
一、环境准备
-
开发环境要求
- JDK 17
- Maven 3.6+(用于依赖管理)
- Spring Boot 3.x
- 数据库(如 MySQL 5.7+)
-
创建springboot项目
2.1 打开 IntelliJ IDEA
- 选择
File
→New
→Project
(或使用快捷键Ctrl + Alt + Shift + N
)。
2.2 选择项目类型
- 左侧选择
Spring Initializr
。 - 确保
Language
为Java
,Build System
为Maven
(推荐)。
- 3 项目基础信息
- Name:自定义项目名称(如
springboot3-demo
)。 - Group 和 Artifact:填写项目的包名和唯一标识符(如
com.example
)。 - Java:选择
17
或更高版本(Spring Boot 3 最低要求)。 - Spring Boot:选择
3.0.0
或更高版本。
2.4 添加依赖
- 点击
Add Dependencies
,搜索并添加以下依赖:- Spring Web:用于构建 RESTful API 和 Web 应用。
- MySQL Driver:MySQL 数据库连接驱动。
2.5 项目位置和创建
- 指定项目存储路径,点击
Create
。
- 选择
-
修改IDEA的相关配置
3.1 更改jdk配置:
- 点击顶部菜单:
File
→Project Structure
- 在左侧面板选择
Project Settings
→Project
- 在右侧的
SDK
下拉菜单中选择JDK 17 - 在
Project language level
下拉菜单中选择与 JDK 版本匹配的语言级别
3.2 修改 IDEA 全局 Maven JDK 配置:
- 点击顶部菜单:
File
→Settings
- 定位
Build, Execution, Deployment
→Build Tools
→Maven
→Run
- 在右侧面板
JRE
字段中选择已安装的 JDK 17 版本
- 点击顶部菜单:
-
Maven 依赖配置
在
pom.xml
中添加以下依赖:<!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.4</version> </dependency> <!-- lombook --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency>
-
修改application.properties文件
更改文件名:
- 修改application.properties为application.yml
添加相关配置
mybatis: configuration: #配置mybatis的日志,指定输出到控制台 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启mybatis的驼峰命名自动映射开关 map-underscore-to-camel-case: true spring: datasource: url: jdbc:mysql://localhost:3306/your_database_name username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver
-
IDEA连接数据库
- 打开 Database 工具窗口:在 IDEA 主界面中,选择
View
->Tool Windows
->Database
,或者直接在右侧侧边栏查找Database
标签。 - 选择数据源:点击
Database
工具窗口中的+
按钮,选择Data Source
,再选择MySQL
。如果是其他类型的数据库,则选择对应的选项。 - 下载驱动:如果是首次使用且没有驱动,IDEA 会在
Driver
处提示没有下载对应数据库类型的驱动,直接点击提示信息即可自动下载。 - 配置连接信息:
- 连接名称:可自行设置一个便于识别的名称。
- 数据库地址和端口号:连接本地数据库时,
Host
通常填写localhost
,MySQL 默认端口号为3306
。 - 用户名和密码:填写 MySQL 数据库的用户名和密码。
- 数据库名称:可以填写想连接的数据库名,也可以暂时不填,待连接成功后再设置。
- 测试连接:填写完连接信息后,点击
Test Connection
按钮,若显示Successful
,表示连接成功,然后点击OK
按钮完成配置。 - 查看和操作数据库:连接成功后,在
Database
标签下,可以查看数据库结构,如数据库中的表、视图等。还可以右键点击数据库连接,选择New Query Console
来编写和执行 SQL 查询,对数据库进行各种操作。
- 打开 Database 工具窗口:在 IDEA 主界面中,选择
二、创建数据库与表
CREATE DATABASE mybatis_db;
USE mybatis_db;
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100),
create_time DATETIME
);
INSERT INTO user (username, password, email, create_time)
VALUES ('张三', '123456', 'zhangsan@example.com', NOW()),
('李四', 'abcdef', 'lisi@example.com', NOW());
三、创建实体类与Mapper
-
实体类(Entity)
在com.example.entity
包下创建User.java
:package com.example.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String username; private String password; private String email; private Date createTime; }
-
Mapper 接口
在com.example.mapper
包下创建UserMapper.java
:public interface UserMapper { // 根据 ID 查询用户 User findById(Integer id); // 查询所有用户 List<User> findAll(); // 插入用户 int insert(User user); // 更新用户 int update(User user); // 删除用户 int delete(Integer id); }
四、创建Controller和Service
-
Controller类
package com.example.controller; import com.example.Service.UserService; import com.example.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/findAll") public List<User> findAll(){ List<User> all = userService.findAll(); return all; } }
-
Service接口
package com.example.Service; import com.example.entity.User; import java.util.List; public interface UserService { // 根据 ID 查询用户 User findById(Integer id); // 查询所有用户 List<User> findAll(); // 插入用户 int insert(User user); // 更新用户 int update(User user); // 删除用户 int delete(Integer id); }
-
Service实现类
package com.example.Service.impl; import com.example.Service.UserService; import com.example.entity.User; import com.example.mapper.UserMapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User findById(Integer id) { return null; } @Override public List<User> findAll() { List<User> all = userMapper.findAll(); return all; } @Override public int insert(User user) { return 0; } @Override public int update(User user) { return 0; } @Override public int delete(Integer id) { return 0; } }
五、创建Mapper.xml文件
-
Mapper.xml文件
-
在
src/main/resources
目录下按照com/example/mapper
的方式创建包,创建成功后右键点击在文件夹打开,检查是不是按照包夹包的方式创建的。 -
在
com.example.mapper
包下创建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"> <mapper namespace="com.example.mapper.UserMapper"> <select id="findAll" resultType="com.example.entity.User"> select * from user; </select> </mapper>
注意:
- namespace 里是 UserMapper接口的路径
- id 里是 UserMapper接口里的方法名
- resultType 里是返回对象的全类名 (找到对应的类,右键选择
Copy Path/Reference
即可复制全类名)
-
六、测试
用调试软件使用GET方法向 http://localhost:8080/user/findAll
发送请求,成功返回数据