Spring Boot 3.3 + MyBatis 基础教程:从入门到实践

news2025/6/8 13:03:46

在这里插入图片描述

Spring Boot 3.3 + MyBatis 基础教程:从入门到实践

在当今的Java开发领域,Spring Boot和MyBatis是构建高效、可维护的后端应用的两个强大工具。Spring Boot简化了Spring应用的初始搭建和开发过程,而MyBatis则提供了一种灵活的ORM(对象关系映射)解决方案。本文将介绍如何在Spring Boot 3.3中集成MyBatis,并通过一个简单的用户管理系统示例来展示其基本用法。同时,我们也会深入探讨MyBatis的实现原理,并通过类图来帮助理解其内部机制。

一、项目搭建

1. 创建Spring Boot项目

首先,使用Spring Initializr(https://start.spring.io/)创建一个Spring Boot项目,选择以下依赖:

  • Spring Web
  • MyBatis Framework
  • MySQL Driver

生成项目后,将项目导入到你的IDE中(如IntelliJ IDEA或Eclipse)。

2. 添加依赖

pom.xml文件中,确保添加了以下依赖:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MyBatis Spring Boot Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.4</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- Spring Boot Starter Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3. 配置数据源和MyBatis

application.yml文件中,配置数据源和MyBatis的相关信息:

spring:
  application:
    name: spring-boot-demo
  datasource:
    url: jdbc:mysql://localhost:3306/db_spring_boot_demo?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  • spring.datasource.*:配置数据库连接信息。
  • mybatis.mapper-locations:指定MyBatis映射文件的位置。

二、创建实体类

创建一个简单的User实体类,用于表示用户信息:

package com.example.demo.model;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String password;
}
  • 使用@Data注解来自动生成getter和setter方法。

三、创建Mapper接口

MyBatis通过Mapper接口来定义数据库操作。创建UserMapper接口:

package com.example.demo.mapper;

import com.example.demo.model.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {
	// 也可以用@Select @Update等注解来定义相关的sql语句,不用xml配图
    User selectById(Long id);
    void insert(User user);
    void update(User user);
    void deleteById(Long id);
    List<User> getAll();
}

直接代码定义SQL语句

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User selectById(Long id);

    @Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(User user);

    @Update("UPDATE users SET username = #{username}, password = #{password} WHERE id = #{id}")
    void update(User user);

    @Delete("DELETE FROM users WHERE id = #{id}")
    void deleteById(Long id);

    @Select("SELECT * FROM users")
    List<User> getAll();
}

使用XML配置SQL

src/main/resources/mapper目录下创建UserMapper.xml文件,定义SQL语句:

<?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.demo.mapper.UserMapper">

    <select id="selectById" parameterType="long" resultType="com.example.demo.model.User">
        SELECT * FROM users WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="com.example.demo.model.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO users(username, password) VALUES(#{username}, #{password})
    </insert>

    <update id="update" parameterType="com.example.demo.model.User">
        UPDATE users SET username = #{username}, password = #{password} WHERE id = #{id}
    </update>

    <delete id="deleteById" parameterType="long">
        DELETE FROM users WHERE id = #{id}
    </delete>

    <select id="getAll" resultType="com.example.demo.model.User">
        SELECT * FROM users
    </select>

</mapper>
  • namespace:指定Mapper接口的全限定名。
  • 每个SQL语句通过<select><insert><update><delete>标签定义。

四、创建服务层

服务层是业务逻辑的核心部分。创建UserService类:

package com.example.demo.service;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User createUser(User user) {
        userMapper.insert(user);
        return user;
    }

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    public List<User> getAllUsers() {
        return userMapper.getAll();
    }

    public void updateUser(User user) {
        userMapper.update(user);
    }

    public void deleteUserById(Long id) {
        userMapper.deleteById(id);
    }
}
  • 使用@Service注解标记这是一个服务类。
  • 通过构造函数注入UserMapper

五、创建控制器

控制器层用于处理HTTP请求。创建UserController类:

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        return ResponseEntity.ok(userService.createUser(user));
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id));
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
        return ResponseEntity.noContent().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUserById(@PathVariable Long id) {
        userService.deleteUserById(id);
        return ResponseEntity.noContent().build();
    }
}
  • 使用@RestController注解标记这是一个REST控制器。
  • 使用@RequestMapping定义请求路径。
  • 使用@Autowired注入UserService

六、MyBatis实现原理简述

MyBatis是一个半自动化的ORM框架,它通过以下机制实现数据访问:

  1. SQL映射

    • MyBatis通过Mapper接口和注解(或XML配置)将Java对象与SQL语句进行映射。
    • UserMapper中,@Select@Insert等注解定义了SQL语句和Java方法的对应关系。
  2. 动态SQL

    • MyBatis支持动态SQL,可以根据传入的参数动态生成SQL语句。
    • 例如,#{username}会被替换为实际的参数值。
  3. SQL会话管理

    • MyBatis通过SqlSession管理数据库会话,负责执行SQL语句、获取映射器和管理事务。
    • 在Spring Boot中,SqlSession的生命周期由Spring管理。
  4. 映射器代理

    • MyBatis为Mapper接口生成代理对象,当调用Mapper方法时,会通过代理机制执行对应的SQL语句。
    • 例如,调用userMapper.insert(user)时,MyBatis会根据注解生成并执行SQL语句。
  5. 结果映射

    • MyBatis将查询结果自动映射为Java对象。
    • selectById方法中,查询结果会被映射为User对象。

MyBatis主要类图(Mermaid格式)

以下是MyBatis主要类的UML类图,使用Mermaid格式表示:

creates
uses
has
uses
uses
creates
has
creates
implements
SqlSessionFactory
+open()
+getConfiguration()
SqlSession
+selectOne()
+selectList()
+insert()
+update()
+delete()
+getMapper()
Configuration
+getEnvironment()
+getMapperRegistry()
Environment
+getDataSource()
+getTransactionFactory()
DataSource
+getConnection()
TransactionFactory
+newTransaction()
Transaction
+commit()
+rollback()
MapperRegistry
+getMappers()
MapperProxy
+invoke()
Mapper
+selectById()
+insert()
+update()
+deleteById()
+getAll()
  • SqlSessionFactory:负责创建SqlSession实例。
  • SqlSession:负责执行SQL语句、获取映射器和管理事务。
  • Configuration:存储MyBatis的配置信息,包括环境配置、数据源、事务管理器和映射器。
  • Environment:定义了数据源和事务管理器的配置。
  • DataSource:提供数据库连接。
  • TransactionFactory:用于创建事务管理器。
  • Transaction:管理事务的提交和回滚。
  • MapperRegistry:管理映射器接口。
  • MapperProxy:为映射器接口生成代理对象。
  • Mapper:映射器接口,定义了数据库操作方法。

七、运行项目

启动Spring Boot应用后,你可以通过以下RESTful API进行测试:

  • 创建用户POST /api/users
  • 获取用户GET /api/users/{id}
  • 获取所有用户GET /api/users
  • 更新用户PUT /api/users/{id}
  • 删除用户DELETE /api/users/{id}

http测试脚本

IntelliJ http接口请求脚本

### 创建用户 POST /api/users
POST http://localhost:8080/api/users
Content-Type: application/json

{
  "username": "john_doe——2",
  "password": "securePassword123"
}

### 根据ID查询用户 GET /api/users/{id}
GET http://localhost:8080/api/users/1

### 查询所有用户 GET /api/users
GET http://localhost:8080/api/users

### 更新用户 PUT /api/users/{id}
PUT http://localhost:8080/api/users/1
Content-Type: application/json

{
  "username": "john_doe_updated",
  "password": "newSecurePassword456"
}

### 删除用户 DELETE /api/users/{id}
DELETE http://localhost:8080/api/users/1

九、总结

通过本文,我们展示了如何在Spring Boot 3.3中集成MyBatis,并实现了一个简单的用户管理系统。MyBatis的灵活性和强大的SQL映射能力使其成为Java开发中常用的ORM框架之一。同时,通过Mermaid格式的类图,我们深入探讨了MyBatis的实现原理,帮助你更好地理解其内部机制。

希望本文对你有所帮助!如果你有任何问题或建议,欢迎留言交流。


以我之思,借AI之力

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2404160.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

征文投稿:如何写一份实用的技术文档?——以软件配置为例

&#x1f4dd; 征文投稿&#xff1a;如何写一份实用的技术文档&#xff1f;——以软件配置为例 目录 [TOC](目录)&#x1f9ed; 技术文档是通往成功的“说明书”&#x1f4a1; 一、明确目标读者&#xff1a;他们需要什么&#xff1f;&#x1f4cb; 二、结构清晰&#xff1a;让读…

tensorflow image_dataset_from_directory 训练数据集构建

以数据集 https://www.kaggle.com/datasets/vipoooool/new-plant-diseases-dataset 为例 目录结构 训练图像数据集要求&#xff1a; 主目录下包含多个子目录&#xff0c;每个子目录代表一个类别。每个子目录中存储属于该类别的图像文件。 例如 main_directory/ ...cat/ ...…

GOOUUU ESP32-S3-CAM 果云科技开发板开发指南(一)(超详细!)Vscode+espidf 通过摄像头拍摄照片并存取到SD卡中,文末附源码

看到最近好玩的开源项目比较多&#xff0c;就想要学习一下esp32的开发&#xff0c;目前使用比较多的ide基本上是arduino、esp-idf和platformio&#xff0c;前者编译比较慢&#xff0c;后两者看到开源大佬的项目做的比较多&#xff0c;所以主要学习后两者。 本次使用的硬件是GO…

全流程开源!高德3D贴图生成系统,白模一键生成真实感纹理贴图

导读 MVPainter 随着3D生成从几何建模迈向真实感还原&#xff0c;贴图质量正逐渐成为决定3D资产视觉表现的核心因素。我们团队自研的MVPainter系统&#xff0c;作为业内首个全流程开源的3D贴图生成方案&#xff0c;仅需一张参考图与任意白模&#xff0c;即可自动生成对齐精确…

html 滚动条滚动过快会留下边框线

滚动条滚动过快时&#xff0c;会留下边框线 但其实大部分时候是这样的&#xff0c;没有多出边框线的 滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行为有关。这种问题可能出现在使用了自定义滚动条样式的情况下。 注意&#xff1a;使用方法 6 好使&#xff0c;其它…

数据通信与计算机网络——数据与信号

主要内容 模拟与数字 周期模拟信号 数字信号 传输减损 数据速率限制 性能 注&#xff1a;数据必须被转换成电磁信号才能进行传输。 一、模拟与数字 数据以及表示数据的信号可以使用模拟或者数字的形式。数据可以是模拟的也可以是数字的&#xff0c;模拟数据是连续的采用…

【LLM大模型技术专题】「入门到精通系列教程」LangChain4j与Spring Boot集成开发实战指南

LangChain4j和SpringBoot入门指南 LangChain4jLangchain4j API语言模型消息类型内存对象ChatMemory接口的主要实现设置 API 密钥SpringBoot Configuration配置ChatLanguageModelStreamingChatLanguageModel初始化ChatModel对象模型配置分析介绍说明通过JavaConfig创建ChatModel…

Vue3 GSAP动画库绑定滚动条视差效果 绑定滚动条 滚动条动画 时间轴

介绍 GSAP 用于创建高性能、可控制的动画效果。由 GreenSock 团队开发&#xff0c;旨在提供流畅、快速、稳定的动画效果&#xff0c;并且兼容各种浏览器。 提供了多个插件&#xff0c;扩展了动画的功能&#xff0c;如 ScrollTrigger&#xff08;滚动触发动画&#xff09;、Dra…

grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!

还在深夜盯着 Grafana 图表手动排查问题&#xff1f;今天推荐一个让 AI 能“读图说话”的开源神器 —— grafana-mcp-analyzer。 想象一下这样的场景&#xff1a; 凌晨3点&#xff0c;服务器告警响起。。。你睁着惺忪的眼睛盯着复杂的监控图表 &#x1f635;‍&#x1f4ab;花…

【题解-洛谷】B3622 枚举子集(递归实现指数型枚举)

题目&#xff1a;B3622 枚举子集&#xff08;递归实现指数型枚举&#xff09; 题目描述 今有 n n n 位同学&#xff0c;可以从中选出任意名同学参加合唱。 请输出所有可能的选择方案。 输入格式 仅一行&#xff0c;一个正整数 n n n。 输出格式 若干行&#xff0c;每行…

(LeetCode 每日一题)3170. 删除星号以后字典序最小的字符串(贪心+栈)

题目&#xff1a;3170. 删除星号以后字典序最小的字符串 思路&#xff1a;贪心栈&#xff0c;时间复杂度0(n)。 对于每一个‘ * ’&#xff0c;优先选最右边的最小字符&#xff0c;才会使最终得到的字符串最小。 用栈&#xff0c;来记录每个字符的位置下标。细节看注释。 C版本…

使用 HTML + JavaScript 实现文章逐句高亮朗读功能

在这个信息爆炸的时代&#xff0c;我们每天都要面对大量的文字阅读。无论是学习、工作还是个人成长&#xff0c;阅读都扮演着至关重要的角色。然而&#xff0c;在快节奏的生活中&#xff0c;我们往往难以找到足够的安静时间专注于阅读。本文用 HTML JavaScript 实现了一个基于…

双碳时代,能源调度的难题正从“发电侧”转向“企业侧”

安科瑞刘鸿鹏 摘要 在“双碳”战略和能源结构转型的大背景下&#xff0c;企业储能电站逐步成为提升能源利用效率、增强用能韧性的重要手段。随着系统规模扩大与运行复杂度提升&#xff0c;如何对光伏、储能、负荷等流进行实时调控&#xff0c;成为智慧用能的关键。ACCU100微…

3. 简述node.js特性与底层原理

&#x1f63a;&#x1f63a;&#x1f63a; 一、Node.js 底层原理&#xff08;简化版&#xff09; Node.js 是一个 基于 Chrome V8 引擎构建的 JavaScript 运行时&#xff0c;底层核心由几部分组成&#xff1a; 组成部分简要说明 1.V8 引擎 将 JS 编译成机器码执行&#xff0…

OpenCV CUDA模块图像处理------创建一个模板匹配(Template Matching)对象函数createTemplateMatching()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 创建一个用于在 GPU 上执行模板匹配的 TemplateMatching 对象。 该函数返回一个指向 TemplateMatching 的智能指针&#xff08;Ptr&#xff09;…

【Kubernetes】K8s 之 ETCD - 恢复备份

ETCD 是一个高可用的分布式键值存储&#xff0c;常用于存储配置信息和服务发现等。当系统出现故障或数据损坏时&#xff0c;能够快速恢复成先前的状态是维护系统稳定性的关键。ETCD 提供了备份和恢复功能&#xff0c;以确保数据持久性和可靠性&#xff0c;一起来看看如何操作吧…

RabbitMQ 学习

MQ 的相关概念 什么是 MQ MQ&#xff08;message queue&#xff09;&#xff0c;从字面意思上看&#xff0c;本质是个队列&#xff0c;FIFO 先入先出&#xff0c;只不过队列中存放的内容是 message 而已&#xff0c;还是一种跨进程的通信机制&#xff0c;用于上下游传递消息。…

如何轻松、安全地管理密码(新手指南)

很多人会为所有账户使用相同、易记的密码&#xff0c;而且常常多年不换。虽然这样方便记忆&#xff0c;但安全性非常低。 您可能听说过一些大型网站的信息泄露事件&#xff0c;同样的风险也可能存在于您的WordPress网站中。如果有不法分子获取了访问权限&#xff0c;您的网站和…

AWS App Mesh实战:构建可观测、安全的微服务通信解决方案

摘要&#xff1a;本文详解如何利用AWS App Mesh统一管理微服务间通信&#xff0c;实现精细化流量控制、端到端可观测性与安全通信&#xff0c;提升云原生应用稳定性。 一、什么是AWS App Mesh&#xff1f; AWS App Mesh 是一种服务网格&#xff08;Service Mesh&#xff09;解…

9.axios底层原理,和promise的对比(2)

&#x1f63a;&#x1f63a;&#x1f63a; 和promise的对比 完全可以直接使用 Promise 来发 HTTP 请求&#xff0c;比如用原生 fetch Promise 就可以实现网络请求功能&#x1f447; ✅ 用 Promise fetch 的写法&#xff08;原生&#xff09; fetch(‘https://api.example.c…