【SpringBoot核心】Spring Boot + MyBatis 深度整合与最佳实践

目录

  1. 引言
  2. Spring Boot 基础回顾
  3. MyBatis 核心概念解析
  4. Spring Boot 整合 MyBatis
  5. MyBatis 高级特性
  6. Spring Boot + MyBatis 最佳实践
  7. 性能优化与扩展
  8. 实战案例:电商系统开发
  9. 常见问题与解决方案
  10. 总结与展望

1. 引言

1.1 技术背景与现状

在现代企业级应用开发中,数据持久化是一个核心需求。随着Java生态系统的不断发展,出现了多种ORM框架,如Hibernate、MyBatis、JPA等。其中,MyBatis因其灵活性、高性能和易用性,在企业级应用中占据了重要地位。

Spring Boot作为Spring框架的"约定优于配置"实现,极大地简化了Spring应用的初始搭建和开发过程。将Spring Boot与MyBatis结合,可以充分发挥两者的优势,构建高效、可维护的数据访问层。

1.2 为什么选择Spring Boot + MyBatis

  1. 开发效率高:Spring Boot的自动配置和起步依赖大大减少了样板代码
  2. 灵活性好:MyBatis允许开发者直接编写SQL,保持了对SQL的完全控制
  3. 性能优异:MyBatis避免了Hibernate等框架可能产生的复杂查询问题
  4. 易于集成:Spring Boot对MyBatis有良好的官方支持
  5. 生态丰富:两者都有庞大的社区和丰富的插件支持

1.3 本文内容概览

本文将全面介绍Spring Boot与MyBatis的整合与实践,从基础配置到高级特性,再到性能优化和实战案例,为开发者提供一站式解决方案。

2. Spring Boot 基础回顾

2.1 Spring Boot 核心特性

Spring Boot的核心设计理念是"约定优于配置",其主要特性包括:

  1. 自动配置:根据classpath中的jar包自动配置Spring应用
  2. 起步依赖:简化Maven/Gradle配置,一键式添加功能模块
  3. Actuator:提供生产级监控和管理端点
  4. 嵌入式容器:内置Tomcat、Jetty等Servlet容器
  5. 外部化配置:支持多种格式的配置文件和环境变量

2.2 Spring Boot 项目结构

标准的Spring Boot项目结构如下:

src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── demo/
│   │               ├── DemoApplication.java       # 启动类
│   │               ├── config/                   # 配置类
│   │               ├── controller/               # 控制器
│   │               ├── service/                  # 服务层
│   │               ├── dao/                      # 数据访问层
│   │               └── model/                    # 实体类
│   └── resources/
│       ├── static/                               # 静态资源
│       ├── templates/                            # 模板文件
│       ├── application.yml                       # 主配置文件
│       └── mapper/                               # MyBatis映射文件
└── test/                                         # 测试代码

2.3 Spring Boot 自动配置原理

Spring Boot的自动配置是通过@EnableAutoConfiguration注解实现的,其核心机制包括:

  1. 条件注解:如@ConditionalOnClass@ConditionalOnMissingBean
  2. 自动配置类:位于META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
  3. 配置属性:通过@ConfigurationProperties绑定外部配置

示例:查看自动配置报告

# 启用debug日志查看自动配置报告
logging.level.root=debug

或者在启动时添加--debug参数:

java -jar myapp.jar --debug

3. MyBatis 核心概念解析

3.1 MyBatis 架构概述

MyBatis的整体架构分为三层:

  1. 基础支撑层:事务管理、连接池、缓存、日志等基础设施
  2. 核心处理层:配置解析、参数映射、SQL解析、SQL执行、结果集映射
  3. 接口层:SqlSession API、Mapper接口

3.2 核心组件详解

3.2.1 SqlSessionFactory

SqlSessionFactory是MyBatis的核心对象,用于创建SqlSession。通常一个应用只需要一个SqlSessionFactory实例。

构建方式:

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3.2.2 SqlSession

SqlSession代表一次数据库会话,线程不安全,每次使用后应该关闭。主要方法包括:

  • selectOne():查询单个对象
  • selectList():查询对象列表
  • insert():插入数据
  • update():更新数据
  • delete():删除数据
  • commit():提交事务
  • rollback():回滚事务
3.2.3 Mapper 接口

Mapper接口是MyBatis的核心概念之一,通过动态代理技术将接口方法与SQL语句绑定。示例:

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

3.3 XML 映射文件

MyBatis的XML映射文件包含以下主要元素:

  1. <select>:查询语句
  2. <insert>:插入语句
  3. <update>:更新语句
  4. <delete>:删除语句
  5. <sql>:可重用的SQL片段
  6. <resultMap>:结果集映射

示例:

<mapper namespace="com.example.mapper.UserMapper"><resultMap id="userResultMap" type="User"><id property="id" column="id"/><result property="username" column="username"/><result property="email" column="email"/></resultMap><select id="selectUser" resultMap="userResultMap">SELECT * FROM users WHERE id = #{id}</select>
</mapper>

3.4 动态SQL

MyBatis提供了强大的动态SQL功能,主要元素包括:

  1. <if>:条件判断
  2. <choose>/<when>/<otherwise>:多条件选择
  3. <trim>/<where>/<set>:辅助处理SQL片段
  4. <foreach>:循环遍历集合

示例:

<select id="findUsers" resultType="User">SELECT * FROM users<where><if test="username != null">AND username like #{username}</if><if test="email != null">AND email = #{email}</if></where>
</select>

4. Spring Boot 整合 MyBatis

4.1 项目初始化

4.1.1 使用Spring Initializr创建项目

可以通过https://start.spring.io或IDE插件创建Spring Boot项目,添加以下依赖:

  • Spring Web
  • MyBatis Framework
  • MySQL Driver (或其他数据库驱动)
  • Lombok (可选,简化代码)
4.1.2 Maven依赖配置
<dependencies><!-- Spring Boot Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- MyBatis Starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.3</version></dependency><!-- MySQL Connector --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- Test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

4.2 基础配置

4.2.1 数据源配置

application.yml中配置数据源:

spring:datasource:url: jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC&characterEncoding=utf8username: rootpassword: passworddriver-class-name: com.mysql.cj.jdbc.Driverhikari:pool-name: HikariCPmaximum-pool-size: 20minimum-idle: 10idle-timeout: 30000max-lifetime: 60000connection-timeout: 30000
4.2.2 MyBatis 基本配置
mybatis:mapper-locations: classpath:mapper/*.xml  # XML映射文件位置type-aliases-package: com.example.model   # 实体类包名configuration:map-underscore-to-camel-case: true     # 自动驼峰命名转换default-fetch-size: 100                # 默认获取数量default-statement-timeout: 30           # 超时时间(秒)

4.3 基础CRUD实现

4.3.1 实体类定义
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private Long id;private String username;private String password;private String email;private Date createTime;private Date updateTime;
}
4.3.2 Mapper接口定义
@Mapper
public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User findById(Long id);@Insert("INSERT INTO users(username, password, email, create_time, update_time) " +"VALUES(#{username}, #{password}, #{email}, now(), now())")@Options(useGeneratedKeys = true, keyProperty = "id")int insert(User user);@Update("UPDATE users SET username=#{username}, email=#{email}, update_time=now() WHERE id=#{id}")int update(User user);@Delete("DELETE FROM users WHERE id=#{id}")int delete(Long id);@Select("SELECT * FROM users")List<User> findAll();
}
4.3.3 Service层实现
@Service
@RequiredArgsConstructor
public class UserService {private final UserMapper userMapper;public User getUserById(Long id) {return userMapper.findById(id);}public List<User> getAllUsers() {return userMapper.findAll();}public int createUser(User user) {return userMapper.insert(user);}public int updateUser(User user) {return userMapper.update(user);}public int deleteUser(Long id) {return userMapper.delete(id);}
}
4.3.4 Controller层实现
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {private final UserService userService;@GetMapping("/{id}")public ResponseEntity<User> getUser(@PathVariable Long id) {User user = userService.getUserById(id);return ResponseEntity.ok(user);}@GetMappingpublic ResponseEntity<List<User>> getAllUsers() {List<User> users = userService.getAllUsers();return ResponseEntity.ok(users);}@PostMappingpublic ResponseEntity<Void> createUser(@RequestBody User user) {userService.createUser(user);return ResponseEntity.status(HttpStatus.CREATED).build();}@PutMapping("/{id}")public ResponseEntity<Void> updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.updateUser(user);return ResponseEntity.ok().build();}@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUser(@PathVariable Long id) {userService.deleteUser(id);return ResponseEntity.noContent().build();}
}

4.4 XML映射方式实现

4.4.1 创建XML映射文件

resources/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"><resultMap id="userResultMap" type="User"><id property="id" column="id"/><result property="username" column="username"/><result property="password" column="password"/><result property="email" column="email"/><result property="createTime" column="create_time"/><result property="updateTime" column="update_time"/></resultMap><select id="findById" resultMap="userResultMap">SELECT * FROM users WHERE id = #{id}</select><insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">INSERT INTO users(username, password, email, create_time, update_time)VALUES(#{username}, #{password}, #{email}, now(), now())</insert><update id="update" parameterType="User">UPDATE users SET username=#{username}, email=#{email}, update_time=now()WHERE id=#{id}</update><delete id="delete">DELETE FROM users WHERE id=#{id}</delete><select id="findAll" resultMap="userResultMap">SELECT * FROM users</select>
</mapper>
4.4.2 修改Mapper接口
@Mapper
public interface UserMapper {User findById(Long id);int insert(User user);int update(User user);int delete(Long id);List<User> findAll();
}

4.5 分页查询实现

4.5.1 添加分页依赖
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>2.1.0</version>
</dependency>
4.5.2 配置分页插件
pagehelper:helper-dialect: mysqlreasonable: truesupport-methods-arguments: trueparams: count=countSql
4.5.3 实现分页查询
@Service
@RequiredArgsConstructor
public class UserService {private final UserMapper userMapper;public PageInfo<User> getUsersByPage(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);List<User> users = userMapper.findAll();return new PageInfo<>(users);}
}@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {private final UserService userService;@GetMapping("/page")public ResponseEntity<PageInfo<User>> getUsersByPage(@RequestParam(defaultValue = "1") int pageNum,@RequestParam(defaultValue = "10") int pageSize) {PageInfo<User> pageInfo = userService.getUsersByPage(pageNum, pageSize);return ResponseEntity.ok(pageInfo);}
}

5. MyBatis 高级特性

5.1 动态SQL高级用法

5.1.1 <choose>/<when>/<otherwise>示例
<select id

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

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

相关文章

力扣第77题-组合-力扣第78题-子集

力扣链接:77. 组合 - 力扣&#xff08;LeetCode&#xff09; 给定两个整数 n 和 k&#xff0c;返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回答案。 示例 1&#xff1a; 输入&#xff1a;n 4, k 2 输出&#xff1a; [[2,4],[3,4],[2,3],[1,2],[1,3…

嵌入式MTD设备与Flash管理解析

理解MTD是嵌入式系统中处理Flash存储的关键一步&#xff01;我来帮你梳理清楚&#xff1a; MTD 是什么&#xff1f; MTD 是 Memory Technology Device 的缩写&#xff0c;中文常译为内存技术设备。它是 Linux 内核及其衍生系统&#xff08;如嵌入式 Linux&#xff09;中用于管…

基于 GEE 利用 Sentinel-2 数据计算并下载植被指数数据

目录 1 植被指数 2 完整代码 3 运行结果 1 植被指数 植被指数全名NDVI归一化差值植被指数GNDVI绿色归一化差值植被指数EVI增强植被指数EVI2双波段增强植被指数DVI差值植被指数GDVI绿色差植被值指数RVI比值植被指数SAVI土壤调整植被指数OSAVI优化土壤调整植被指数MSAVI修改…

python基础23(2025.6.29)分布式爬虫(增量式爬虫去重)redis应用_(未完成!)

本次写一个爬取网易新闻的案例。因为redis能处理高并发&#xff0c;存储数据也可以&#xff0c;故不用mysql。而且新闻网站容易更新很多&#xff0c;而mysql只能持久化存储。 import scrapy import re import json import redis # 用它来去除重复, 记录访问过的urlclass Wang…

Springboot 集成 SpringState 状态机

Springboot 集成 SpringState 状态机 1.SpringState 简介2.状态机示例2.1 项目结构和依赖包2.2 定义事件类和状态类2.3 Spring 事件监听器2.4 状态机持久化类2.4.1 Redis 状态机持久化容器2.4.2 Redis 配置2.4.3 状态机监听器 2.5 装机器容器2.6 状态机事件发送器2.7 状态机配置…

实战四:基于PyTorch实现猫狗分类的web应用【2/3】

​一、需求描述 实战四分为三部分来实现&#xff0c;第二部分是基于PyTorch的猫狗图像可视化训练的教程&#xff0c;实现了一个完整的猫狗分类模型训练流程&#xff0c;使用预训练的ResNet50模型进行迁移学习&#xff0c;并通过SwanLab进行实验跟踪。 效果图 ​二、实现思路 …

对比几个测试云的一些速度

最近被hosting vps主机的速度给困扰了&#xff0c;干脆放下手中的活 测试下 test.php放在网站根目录即可 代码如下&#xff1a; <?php /*** 最终版服务器性能测试工具* 测试项目&#xff1a;CPU运算性能、内存读写速度、硬盘IO速度、网络下载速度*/// 配置参数&#xff…

UE5 Grid3D 学习笔记

一、Neighbor Grid 3D 的核心作用 NeighborGrid3D 是一种基于位置的哈希查找结构&#xff0c;将粒子按空间位置划分到网格单元&#xff08;Cell&#xff09;中&#xff0c;实现快速邻近查询&#xff1a; 空间划分&#xff1a;将模拟空间划分为多个三维网格单元&#xff08;Cel…

Spring AI ——在springboot应用中实现基本聊天功能

文章目录 前言测试环境项目构建依赖引入指定openai 相关配置基于 application.yml 配置 Open AI 属性application.yml编写测试类测试请求基于读取后配置请求编写测试接口测试效果展示流式输出前言 AI 技术越来越火爆,作为Java开发人员也不能拖了后腿。 前段时间使用LangChain…

条件概率:不确定性决策的基石

条件概率是概率论中的核心概念&#xff0c;用于描述在已知某一事件发生的条件下&#xff0c;另一事件发生的概率。它量化了事件之间的关联性&#xff0c;是贝叶斯推理、统计建模和机器学习的基础。 本文由「大千AI助手」原创发布&#xff0c;专注用真话讲AI&#xff0c;回归技术…

搭建Flink分布式集群

1. 基础环境&#xff1a; 1.1 安装JDK 本次使用 jdk-11.0.26_linux-x64_bin.tar.gz 解压缩 tar -zxvf jdk-11.0.26_linux-x64_bin.tar.gz -C /usr/local/java/ 配置环境变量&#xff1a; vi /etc/profileJAVA_HOME/usr/local/java/jdk-11.0.26 CLASSPATH.:${JAVA_HOME}/li…

基于ssm校园综合服务系统微信小程序源码数据库文档

摘 要 随着我国经济迅速发展&#xff0c;人们对手机的需求越来越大&#xff0c;各种手机软件也都在被广泛应用&#xff0c;但是对于手机进行数据信息管理&#xff0c;对于手机的各种软件也是备受用户的喜爱&#xff0c;校园综合服务被用户普遍使用&#xff0c;为方便用户能够可…

桌面小屏幕实战课程:DesktopScreen 17 HTTPS

飞书文档http://https://x509p6c8to.feishu.cn/docx/doxcn8qjiNXmw2r3vBEdc7XCBCh 源码参考&#xff1a; /home/kemp/work/esp/esp-idf/examples/protocols/https_request 源码下载方式参考&#xff1a; 源码下载方式 获取网站ca证书 openssl s_client -showcerts -connec…

uniapp上传gitee

右键点击项目&#xff0c;选择git提交&#xff0c;会弹出这样的弹窗 在Message输入框里面输入更新的内容&#xff0c;选择更新过的文件&#xff0c;然后点击commit 然后点击push 后面会让你填写gitee的用户名和密码 用户名就是邮箱 密码就是登录gitee的密码

重写(Override)与重载(Overload)深度解析

在Java面向对象编程中&#xff0c;多态性是一个核心概念&#xff0c;它允许我们以统一的方式处理不同类型的对象。而实现多态性的两种重要机制便是方法的“重写”&#xff08;Override&#xff09;与“重载”&#xff08;Overload&#xff09;。透彻理解这两者之间的区别与联系…

Go 语言中操作 SQLite

sqlite以其无需安装和配置&#xff1a;直接使用数据库文件&#xff0c;无需启动独立的数据库服务进程。 单文件存储&#xff1a;整个数据库&#xff08;包括表、索引、数据等&#xff09;存储在单个跨平台文件中&#xff0c;便于迁移和备份。 在应对的小型应用软件中.有着不可…

【硬核数学】2.3 AI的“想象力”:概率深度学习与生成模型《从零构建机器学习、深度学习到LLM的数学认知》

欢迎来到本系列的第八篇文章。在前七章中&#xff0c;我们已经构建了一个强大的深度学习工具箱&#xff1a;我们用张量来处理高维数据&#xff0c;用反向传播来高效地计算梯度&#xff0c;用梯度下降来优化模型参数。我们训练出的模型在分类、回归等任务上表现出色。 但它们有…

华为云Flexus+DeepSeek征文|Dify平台开发搭建口腔牙科24小时在线问诊系统(AI知识库系统)

引言&#xff1a;为什么需要口腔牙科24小时在线问诊系统&#xff1f; 在口腔医疗领域&#xff0c;“时间”是患者最敏感的需求之一——深夜牙齿突发疼痛、周末想提前了解治疗方案、异地患者无法及时到院……传统“工作时间在线”的咨询模式已无法满足用户需求。同时&#xff0…

嵌入式硬件中电容的基本原理与详解

大家好我们今天重讨论点知识点如下: 1.电容在电路中的作用 2.用生活中水缸的例子来比喻电容 3.电容存储能力原理 4.电容封装的种类介绍电容种类图片辨识 5.X 电容的作用介绍 6.Y 电容的作用介绍7.钽电容的优点及特性 7.钽电容的缺点及特性 8. 铝电解电容的优点及特性…

中央空调控制系统深度解析:从原理到智能AIOT运维

——附水冷式系统全电路图解与技术参数 一、中央空调系统架构与技术演进 1. 两大主流系统对比 技术趋势&#xff1a;2023年全球冷水机组市场占比达68%&#xff08;BSRIA数据&#xff09;&#xff0c;其核心优势在于&#xff1a; - 分区控温精度&#xff1a;0.5℃&#…