当前位置: 首页 > news >正文

Spring Boot 整合 MyBatis 快速入门超详教程

目标:

为了快速入门,我这里演示创建一个简单的用户管理,包含用户列表的增删改查功能。

准备工作:

1 环境搭建: 确保已安装 JDK 1.8+、Maven 3.3+、MySQL 数据库以及 IntelliJ IDEA 。

2 数据库准备: 在 MySQL 中创建名为 user_db 的数据库,并在其中创建名为 user 的表,包含以下字段:

                a) id: 用户 ID,主键,自增

                b) name: 用户名,字符串类型

                c) age: 年龄,整数类型

 建表SQL语句:

CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL,age INT NOT NULL
);

3 创建 Spring Boot 项目: 使用 IDEA 创建一个名为 mybatis-demo 的 Spring Boot 项目,并添加以下依赖:

                a) Spring Web

                b) MyBatis Framework

                c) MySQL Driver

相关教程:

JDK安装教程及Java环境配置

MySql安装教程

MySql基础语法详解

IDEA安装教程

快速创建Spring Boot教程


详细步骤:

1. 项目结构:

mybatis-demo
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── mybatisdemo
│   │   │               ├── MybatisDemoApplication.java
│   │   │               ├── controller
│   │   │               │   └── UserController.java
│   │   │               ├── entity
│   │   │               │   └── User.java
│   │   │               ├── mapper
│   │   │               │   └── UserMapper.java
│   │   │               └── service
│   │   │                   ├── UserServiceImpl.java
│   │   │                   └── UserService.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── mapper
│   │           └── UserMapper.xml
│   └── test
│       └── java
│           └── com
│               └── example
│                   └── mybatisdemo
│                       └── MybatisDemoApplicationTests.java
└── pom.xml

2. 引入依赖 (pom.xml):

<?xml version="1.0" encoding="UTF-8"?>
<project ...><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.7.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency></dependencies>
</project>

3. 配置数据源 (application.properties):

spring.datasource.url=jdbc:mysql://localhost:3306/user_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

4. 创建实体类 (User.java):

package com.example.mybatisdemo.entity;public class User {private Long id;private String name;private Integer age;// Getters and Setters 省略
}

5. 创建 Mapper 接口 (UserMapper.java):

package com.example.mybatisdemo.mapper;import com.example.mybatisdemo.entity.User;
import org.apache.ibatis.annotations.*;@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")User selectById(@Param("id") Long id);@Insert("INSERT INTO user(name, age) VALUES (#{name}, #{age})")@Options(useGeneratedKeys = true, keyProperty = "id")int insert(User user);@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")int update(User user);@Delete("DELETE FROM user WHERE id = #{id}")int deleteById(@Param("id") Long id);@Select("SELECT * FROM user")List<User> selectAllUsers();
}

@Mapper 注解告诉 MyBatis 创建这个接口的实现类。

  • @Select、@Insert、@Update 和 @Delete 注解分别对应 SQL 语句的查询、插入、更新和删除操作。

  • @Param("id") 将方法参数 id 绑定到 SQL 语句中的占位符 #{id}。

  • @Options 配置插入操作,useGeneratedKeys = true 表示使用数据库生成的主键,keyProperty = "id" 表示将生成的主键赋值给实体类 User 的 id 属性。

6. 创建 Mapper XML 文件 (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.mybatisdemo.mapper.UserMapper"><!-- 根据 ID 查询用户 --><select id="selectById" resultType="com.example.mybatisdemo.entity.User">SELECT * FROM user WHERE id = #{id}</select><!-- 新增用户 --><insert id="insert" keyProperty="id" useGeneratedKeys="true">INSERT INTO user(name, age) VALUES (#{name}, #{age})</insert><!-- 更新用户信息 --><update id="update">UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}</update><!-- 根据 ID 删除用户 --><delete id="deleteById">DELETE FROM user WHERE id = #{id}</delete><!-- 查询所有用户 --><select id="selectAllUsers" resultType="com.example.mybatisdemo.entity.User">SELECT * FROM user</select></mapper>

解释:

  • <mapper namespace="com.example.mybatisdemo.mapper.UserMapper">: 定义了这个 Mapper XML 文件对应的 Mapper 接口的全限定名。

  • <select>, <insert>, <update>, <delete>: 分别对应 SQL 语句的查询、插入、更新和删除操作。

  • id 属性: 与 Mapper 接口中定义的方法名一致。

  • resultType 属性: 定义查询结果的类型,这里对应 com.example.mybatisdemo.entity.User。

  • #{id}: 使用占位符传入参数。

  • keyProperty="id" 和 useGeneratedKeys="true": 用于获取插入操作后自动生成的主键,并将主键值赋值给实体类的 id 属性。

注意:

  • Mapper XML 文件需要放在 resources/mapper 目录下。

  • Mapper XML 文件名建议与 Mapper 接口名一致,例如 UserMapper.xml。

7. 创建 Service 接口 (UserService.java):

package com.example.mybatisdemo.service;import com.example.mybatisdemo.entity.User;import java.util.List;public interface UserService {User getUserById(Long id);int createUser(User user);int updateUser(User user);int deleteUser(Long id);List<User> getAllUsers();
}

8. 实现 Service 接口 (UserServiceImpl.java):

package com.example.mybatisdemo.service;import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Overridepublic int createUser(User user) {return userMapper.insert(user);}@Overridepublic int updateUser(User user) {return userMapper.update(user);}@Overridepublic int deleteUser(Long id) {return userMapper.deleteById(id);}@Overridepublic List<User> getAllUsers() {return userMapper.selectAllUsers();}
}

@Service 注解将该类标记为 Spring Bean。

  • @Autowired 注解自动注入 UserMapper 实例。

9. 创建 Controller (UserController.java):

package com.example.mybatisdemo.controller;import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PostMappingpublic int createUser(@RequestBody User user) {return userService.createUser(user);}@PutMapping("/{id}")public int updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);return userService.updateUser(user);}@DeleteMapping("/{id}")public int deleteUser(@PathVariable Long id) {return userService.deleteUser(id);}@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}
}

@RestController 注解将该类标记为 RESTful 风格的控制器。

  • @RequestMapping("/users") 定义接口路径前缀。

  • @GetMapping、@PostMapping、@PutMapping、@DeleteMapping 分别对应 GET、POST、PUT、DELETE 请求。

10. 运行项目:

  • 运行 MybatisDemoApplication.java 启动 Spring Boot 应用。

11. 测试接口:

  • 使用 Postman 或浏览器测试以下接口:

    • GET /users: 获取所有用户

    • GET /users/1: 获取 ID 为 1 的用户

    • POST /users: 创建新用户 (请求体: {"name": "John Doe", "age": 30})

    • PUT /users/1: 更新 ID 为 1 的用户信息 (请求体: {"name": "Jane Doe", "age": 25})

    • DELETE /users/1: 删除 ID 为 1 的用户

通过以上步骤,你已经成功创建了一个使用 Spring Boot 和 MyBatis 实现的简单用户管理。

进阶学习:

  • MyBatis 动态 SQL

  • MyBatis 缓存机制

  • MyBatis 一对一、一对多、多对多关联查询

希望这个超详细的教程能够帮助各位看官快速入门 Spring Boot 和 MyBatis!感谢各位看官的观看,下期见,谢谢~


http://www.mrgr.cn/news/49977.html

相关文章:

  • WebGl学习使用attribute变量绘制一个水平移动的点
  • C++的IO流
  • 【微服务】微服务API网关详解:提升系统效率与安全性的关键策略
  • 使用多IP香港站群服务器对网站管理seo优化提升排名有益处
  • 算力共享:优化器和决策器
  • 24款奔驰GLS450升级原厂动态按摩座椅效果怎么样
  • 【C++如何游戏开发】
  • 丝杆支撑座的基础知识
  • 帕累托图(Pareto Chart):至关重要的极少数”原因
  • 国产长芯微LMH9954是高分辨率 32 位模数转换器,LMH9954完全P2P替代ADS1284,ADS1283
  • 用Python构建动态折线图:实时展示爬取数据的指南
  • Node.js版本管理工具 安装NVM (Windows系统和macOS系统) 教程
  • Mybaits系列全解
  • SoapUI、Jmeter、Postman三种接口测试工具的比较分析
  • 资源泄露软件闪退怎么解决?
  • STM32L151 多通道ADC DMA循环扫描STM32CubeIDE STM32CubeMX参考设计
  • 浅谈知识管理平台
  • 满​帮​一​面
  • 【名单】科大睿智祝贺服务企业上榜最新一批DCMM公示名单
  • 电气学习知识点