Mybatis基础

Mybatis基础

2026年5月19日·#javawebai/后端基础Java/Mybatis/SpringBoot/数据库/ORM·1051 字 5 分钟
浏览量加载中...
AI 摘要- DeepSeek

Mybatis是一款优秀的持久层框架,用于简化JDBC开发,支持注解和XML两种方式编写SQL。

Mybatis基础#

定义#

MyBatis 是一款优秀的持久层框架,用于简化JDBC的开发。原本是Apache的开源项目iBatis,2010年迁移至Google Code并改名为MyBatis,2013年11月迁移到Github。

持久层:即数据访问层(DAO),负责与数据库交互。

框架:一套可重用、通用、半成品的软件基础代码模型,在框架基础上开发更高效、规范。

快速入门#

1. 创建SpringBoot工程,导入依赖#

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

2. 数据准备#

实体类 User(位于 com.itheima.pojo 包):

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
private String name;
private Integer age;
}

3. 配置Mybatis#

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/web
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root@1234

4. 编写Mapper接口#

@Mapper
public interface UserMapper {
@Select("select * from user")
public List<User> findAll();
}
  • @Mapper:表示Mybatis中的Mapper接口,运行时框架自动生成代理对象并交由Spring IOC容器管理。
  • @Select:编写select查询语句。

5. 单元测试#

@SpringBootTest
class ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testFindAll() {
List<User> userList = userMapper.findAll();
userList.forEach(System.out::println);
}
}

JDBC vs Mybatis#

JDBC缺点Mybatis解决方案
url/username/password硬编码在代码中配置在 application.properties 中
查询结果解析封装繁琐自动完成映射封装
频繁获取/释放连接造成资源浪费内置数据库连接池技术

数据库连接池#

数据库连接池是一个容器,负责分配、管理数据库连接。

工作原理:

  • 程序启动时,在连接池中创建一定数量的Connection对象。
  • 客户端执行SQL时从连接池获取Connection,执行完毕后归还(复用)。
  • 空闲时间超过最大空闲时间的连接会被自动释放。

好处:资源重用、提升响应速度、避免连接遗漏。

常见连接池产品#

连接池说明
HikariSpringBoot默认,性能优越
Druid阿里巴巴开源,功能强大
C3P0 / DBCP老牌连接池,较少使用

切换为Druid#

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.19</version>
</dependency>
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/web
spring.datasource.druid.username=root
spring.datasource.druid.password=1234

增删改查操作#

注解速查#

操作注解示例
查询@Select@Select("select * from user where id = #{id}")
新增@Insert@Insert("insert into user(...) values(#{...})")
修改@Update@Update("update user set ... where id = #{id}")
删除@Delete@Delete("delete from user where id = #{id}")

参数占位符#

Mybatis提供两种占位符:

占位符特点推荐
#{...}预编译SQL(生成 ?),防SQL注入强烈推荐
${...}直接字符串拼接,存在SQL注入风险不推荐

删除示例#

@Delete("delete from user where id = #{id}")
public Integer deleteById(Integer id);

Integer 返回值表示DML语句影响的记录数。

新增示例#

@Insert("insert into user(username,password,name,age) values(#{username},#{password},#{name},#{age})")
public void insert(User user);

多个参数封装到对象中,通过 #{对象属性名} 引用。

修改示例#

@Update("update user set username=#{username},password=#{password},name=#{name},age=#{age} where id=#{id}")
public void update(User user);

查询示例(多参数)#

@Select("select * from user where username = #{username} and password = #{password}")
public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);

@Param 注解为方法形参起名;基于官方骨架创建的SpringBoot项目中接口编译时会保留方法形参名,@Param 可省略(直接 #{形参名})。

XML映射配置#

使用场景#

  • 注解:简单的增删改查功能。
  • XML:复杂的SQL功能。

注意:一个接口方法对应的SQL语句,要么使用注解,要么使用XML,不可同时配置。

XML配置规范#

  1. XML映射文件名称与Mapper接口名称一致,放在相同包下(同包同名)。
  2. XML映射文件的 namespace 为Mapper接口全限定名。
  3. SQL语句的 id 与Mapper接口方法名一致,返回类型一致。

XML示例#

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="findAll" resultType="com.itheima.pojo.User">
select * from user
</select>
</mapper>

辅助配置#

SQL提示#

在IDEA中配置与MySQL数据库的连接,可在 @Select 注解中获得SQL语法提示和表名/列名校验。

Mybatis日志输出#

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

开启后可在控制台查看执行的SQL语句及参数。

注意事项#

  • 测试类所在包需要与引导类所在包相同。
  • 强烈建议使用 #{} 占位符,防止SQL注入。
  • DML操作建议定义 Integer 返回值接收影响行数。
  • MybatisX是IDEA中快速开发Mybatis的插件,可快速定位Mapper与XML的映射关系。

相关链接#

评论区

[ 标签 ]
# AI37# AI 编程2# AI工具1# AI绘图1# AI辅助开发2# Ajax7# Apifox1# AstrBot3# Astro2# CC Switch1# CDN2# Claude Code1# claudecode2# ClaudeCode1# Cloudflare2# CloudFlare2# CloudFlare-ImgBed3# coc4# CSS10# DeepSeek6# deepseek2# DELETE1# Docker5# EdgeOne3# Gist1# git1# GitHub1# hexo-circle-of-friends1# HTML9# HTTP10# ImageManager1# Java23# java13# JavaScript11# JavaWeb113# JDBC7# JSON2# JUnit1# LangChain25# Linux4# Logback1# Maven17# Muse Spark1# Mybatis1# MyBatis18# MySQL45# MySql1# NapCat1# Node.js1# obsidian2# Obsidian5# OpenCode4# ORM1# PathVariable1# PicGo1# PyCharm1# Python70# RequestBody1# RequestMapping1# RESTful风格1# skills1# Slf4j1# SpringBoot37# SpringMVC5# SQL2# Streamlit5# Svelte2# TailwindCSS1# Telegram3# Tlias2# Vercel1# vscode2# Vue20# Waline3# Web3# WebDAV1# Web基础6# Web开发6# WinSCP1# YAML1# 三层架构1# 中二宣言1# 书籍1# 使用文档10# 写作1# 函数2# 刷步数1# 前端52# 动态1# 动漫1# 包1# 单词2# 博客8# 博客工作流1# 博客开发2# 参数接收1# 友链1# 反思2# 后端48# 图床6# 地图1# 备份2# 大模型1# 奇思妙想1# 存储1# 学习方法6# 学校1# 宝塔面板3# 宝宝10# 实战4# 对象1# 导航栏1# 工具2# 布局2# 开发1# 开发工具1# 开发规范1# 开心1# 异常处理1# 影视2# 微信1# 性能优化2# 总结1# 想法15# 感受1# 感悟11# 指南1# 提示词工程2# 插件5# 故障排除1# 效率工具2# 教程10# 数据分析9# 数据库27# 数据结构1# 文件操作2# 斩神1# 日常95# 日志框架1# 朋友圈1# 朱元璋1# 模块1# 模板1# 正则表达式2# 测试3# 游戏2# 爬虫7# 生活迁移1# 电影2# 电脑1# 碎碎念1# 视觉识别1# 类1# 类型注解1# 网络基础2# 网络教室1# 羊毛2# 脚本2# 脚本工具1# 自动化2# 蓝奏云1# 表单1# 订阅推荐2# 记录2# 评论系统1# 词根1# 词缀1# 说说1# 足迹1# 跑步2# 路径参数1# 转载2# 运动1# 部署11# 部落冲突1# 配置1# 随机图1# 面向对象5# 音乐3# 音标1# 项目实战11# 饮食1# 驼峰命名1# 高德地图1
[ 公告 ]

如果你喜欢,那么欢迎来到我的世界!

了解更多
[ 音乐 ]
封面

音乐

暂未播放

0:000:00
暂无歌词
找不到相关结果。
[ contents ]
[ 全部文章 ]