快速上手mybatis教程

devtools/2025/2/6 3:53:56/

基础知识

MyBatis 是一款优秀的持久层框架,其核心组件主要包括以下部分:

SqlSession

  • 作用:SqlSession 是 MyBatis 的核心接口,负责与数据库进行通信,执行 SQL 语句,并返回查询结果。它是 MyBatis 的一次会话,可以执行多个 SQL 语句。

  • 功能:提供了执行 SQL 语句、获取映射器(Mapper)、管理事务等功能。通过 SqlSession,可以执行数据库的增删改查操作,并获取操作结果。

Executor

  • 作用:Executor 是 MyBatis 用来执行 SQL 语句的接口,是 MyBatis 框架中所有数据库操作的核心。

  • 类型:MyBatis 提供了几种不同类型的 Executor 实现,如 SimpleExecutor、ReuseExecutor 和 BatchExecutor,分别适用于不同的应用场景。

Mapper接口

  • 作用:Mapper 接口是 MyBatis 实现 ORM 映射的核心机制。用户可以通过定义接口来描述数据库表结构,并使用注解或 XML 配置文件指定 SQL 语句。

  • 功能:当调用 Mapper 接口的方法时,MyBatis 会利用动态代理技术拦截这些调用,并根据方法签名生成对应的 statementId。随后,MyBatis 会查找预编译好的 SQL 语句并执行相应的数据库操作。

Configuration

  • 作用:Configuration 类是 MyBatis 所有配置信息的封装。它包含了 MyBatis 运行时所需的所有配置,如数据库连接信息(DataSource)、事务管理器(TransactionManager)、类型处理器(TypeHandlers)、映射器(Mapper)的注册信息等。

  • 功能:提供了框架的全局配置信息,使得 MyBatis 能够根据这些配置完成初始化和功能扩展。

MappedStatement

  • 作用:MappedStatement 是 MyBatis 中最重要的一个类,它封装了 SQL 语句的所有信息,包括 SQL 语句本身、输入参数的类型、返回结果的类型、是否使用缓存等。

  • 功能:在 MyBatis 中,每一个 <select><insert><update><delete> 标签都会被解析成一个 MappedStatement 对象,并存储在 Configuration 对象中。

ParameterHandler

  • 作用:ParameterHandler 是 MyBatis 中用于处理 SQL 语句参数的接口。它负责将用户传递的参数值设置到 SQL 语句的占位符中。

  • 功能:通过与 TypeHandler 的协作,将 Java 类型的参数转换为 JDBC 类型的参数,并设置到 PreparedStatement 的相应位置。

TypeHandler

  • 作用:TypeHandler 是 MyBatis 中用于处理 Java 类型和 JDBC 类型之间转换的接口。

  • 功能:定义了如何将 Java 类型转换为 JDBC 类型(用于设置 SQL 语句的参数),以及如何将 JDBC 类型转换为 Java 类型(用于从结果集中获取数据)。

ResultSetHandler

  • 作用:ResultSetHandler 是 MyBatis 中用于处理 SQL 查询结果集的接口。它负责将 JDBC 的 ResultSet 转换为 Java 对象或集合。

  • 功能:通过与 TypeHandler 的协作,从 ResultSet 中读取数据,并将其转换为 Java 类型的值。然后,它根据 Mapper 接口方法的返回类型,将这些值组装成相应的 Java 对象或集合。

StatementHandler

  • 作用:StatementHandler 是 MyBatis 中用于处理 SQL 语句的执行的接口。它封装了 JDBC 的 Statement 或 PreparedStatement,并提供了执行 SQL 语句的方法。

  • 功能:负责配置 SQL 语句的参数、执行 SQL 语句,并处理执行过程中可能出现的异常。

如何快速上手 MyBatis

  1. 搭建开发环境

    • 引入 MyBatis 依赖:在项目的 pom.xml 文件中添加 MyBatis 的 Maven 依赖。

    • 配置数据库连接:创建 mybatis-config.xml 配置文件,配置数据库连接信息、事务管理器、类型处理器等。

  2. 创建 SqlSessionFactory

    • 使用 SqlSessionFactoryBuilder 创建 SqlSessionFactory 实例,加载 mybatis-config.xml 配置文件。

  3. 获取 SqlSession

    • 通过 SqlSessionFactory.openSession() 方法获取 SqlSession 实例,用于执行数据库操作。

  4. 定义 Mapper 接口

    • 创建 Mapper 接口,定义数据库操作的方法,如 selectByIdinsert 等。

  5. 编写 Mapper XML 文件

    • 创建与 Mapper 接口对应的 XML 文件,编写 SQL 语句,如 <select><insert> 等标签。

  6. 执行数据库操作

    • 通过 SqlSession 获取 Mapper 接口的实例,调用其方法执行数据库操作。

  7. 关闭资源

    • 操作完成后,调用 SqlSession.close() 方法关闭会话,释放资源。


参考案例

1. 数据库准备

首先,创建一个简单的数据库Student,包含以下字段:

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

2. MyBatis 核心组件用途示例

结合一个简单的 Java 应用,展示 MyBatis 的核心组件是如何协同工作的。

核心组件
  1. SqlSessionFactory:负责创建 SqlSession

  2. SqlSession:负责执行 SQL、提交或回滚事务。

  3. Mapper接口:定义数据库操作的接口。

  4. Mapper XML文件:编写 SQL 语句。

  5. Configuration:MyBatis 的全局配置文件。

  6. MappedStatement:存储 SQL 信息。

3. 代码案例

3.1 Maven 依赖

确保在 pom.xml 中添加 MyBatis 和 MySQL 的依赖:

<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.13</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.31</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency>
</dependencies>
3.2 数据库配置文件(db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
username=root
password=123456
3.3 MyBatis 全局配置文件(mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><mappers><mapper resource="mapper/StudentMapper.xml"/></mappers>
</configuration>
3.4 Student 实体类
import lombok.Data;@Data
public class Student {private Integer id;private String name;private Integer age;
}
3.5 StudentMapper 接口
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface StudentMapper {List<Student> getAllStudents();void insertStudent(Student student);Student getStudentById(Integer id);void updateStudent(Student student);void deleteStudentById(Integer id);
}
3.6 StudentMapper.xml 文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.StudentMapper"><select id="getAllStudents" resultType="com.example.model.Student">SELECT * FROM Student</select><insert id="insertStudent" parameterType="com.example.model.Student">INSERT INTO Student (name, age) VALUES (#{name}, #{age})</insert><select id="getStudentById" parameterType="int" resultType="com.example.model.Student">SELECT * FROM Student WHERE id = #{id}</select><update id="updateStudent" parameterType="com.example.model.Student">UPDATE Student SET name = #{name}, age = #{age} WHERE id = #{id}</update><delete id="deleteStudentById" parameterType="int">DELETE FROM Student WHERE id = #{id}</delete>
</mapper>
3.7 工具类(获取 SqlSession)
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class MyBatisUtils {private static SqlSessionFactory sqlSessionFactory;static {try {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}public static SqlSession getSqlSession() {return sqlSessionFactory.openSession();}
}
3.8 测试代码
import com.example.mapper.StudentMapper;
import com.example.model.Student;public class Main {public static void main(String[] args) {// 获取 SqlSession 实例SqlSession sqlSession = MyBatisUtils.getSqlSession();try {// 获取 Mapper 接口StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);// 插入一条数据Student student = new Student();student.setName("张三");student.setAge(20);studentMapper.insertStudent(student);sqlSession.commit(); // 提交事务// 查询所有学生List<Student> students = studentMapper.getAllStudents();for (Student s : students) {System.out.println(s);}// 查询单个学生Student studentById = studentMapper.getStudentById(1);System.out.println(studentById);// 更新学生信息studentById.setName("李四");studentById.setAge(22);studentMapper.updateStudent(studentById);sqlSession.commit();// 删除学生studentMapper.deleteStudentById(1);sqlSession.commit();} finally {// 关闭 SqlSessionsqlSession.close();}}
}

4. 核心组件总结

  1. SqlSessionFactory:通过配置文件加载全局配置信息。

  2. SqlSession:负责执行 SQL、提交或回滚事务。

  3. Mapper接口:抽象了数据库操作。

  4. Mapper XML:实际的 SQL 语句。

  5. Configuration:MyBatis 的全局配置文件。

  6. MappedStatement:存储 SQL 信息(如 getAllStudents)。


http://www.ppmy.cn/devtools/156443.html

相关文章

解决open-webui报错Couldn‘t find ffmpeg or avconv

启动open-webui的时候报错Couldnt find ffmpeg or avconv 具体内容&#xff1a; INFO [open_webui.env] Embedding model set: sentence-transformers/all-MiniLM-L6-v2 E:\py311\Lib\site-packages\pydub\utils.py:170: RuntimeWarning: Couldnt find ffmpeg or avconv - d…

Vue指令v-html

目录 一、Vue中的v-html指令是什么&#xff1f;二、v-html指令与v-text指令的区别&#xff1f; 一、Vue中的v-html指令是什么&#xff1f; v-html指令的作用是&#xff1a;设置元素的innerHTML&#xff0c;内容中有html结构会被解析为标签。 二、v-html指令与v-text指令的区别…

Ubuntu下Tkinter绑定数字小键盘上的回车键(PySide6类似)

设计了一个tkinter程序&#xff0c;在Win下绑定回车键&#xff0c;直接绑定"<Return>"就可以使用主键盘和小键盘的回车键直接“提交”&#xff0c;到了ubuntu下就不行了。经过搜索&#xff0c;发现ubuntu下主键盘和数字小键盘的回车键&#xff0c;名称不一样。…

Netty线上如何做性能调优?

大家好&#xff0c;我是锋哥。今天分享关于【Netty线上如何做性能调优&#xff1f;】面试题。希望对大家有帮助&#xff1b; Netty线上如何做性能调优&#xff1f; 1000道 互联网大厂Java工程师 精选面试题-Java资源分享网 Netty是一个高性能的网络通信框架&#xff0c;广泛应…

【阅读笔记】LED显示屏非均匀度校正

一、背景 发光二极管&#xff08;LED&#xff09;显示屏具有色彩鲜艳、图像清晰、亮度高、驱动电压低、功耗小、耐震动、价格低廉和使用寿命长等优势。LED显示图像的非均匀度是衡量LED显示屏显示质量的指标&#xff0c;非均匀度过高&#xff0c;会导致LED显示图像出现明暗不均…

DeepSeek R1 linux云部署

云平台&#xff1a;AutoDL 模型加载工具&#xff1a;Ollama 参考&#xff1a;https://github.com/ollama/ollama/blob/main/docs/linux.md 下载Ollama 服务器上下载ollama比较慢&#xff0c;因此我使用浏览器先下载到本地电脑上。 https://ollama.com/download/ollama-linux…

Pyside/Pyqt 全部类的层级关系

PySide&#xff08;如PySide6&#xff09;的类层级结构基于Qt框架&#xff0c;以下是主要模块及其核心类的层级关系概览。由于类数量庞大&#xff0c;此处仅列出关键类和继承关系&#xff1a; 1. QtCore 模块 基础类与工具 QObject (所有Qt对象的基类) QCoreApplication (控制…

代码随想录算法训练营Day35

第九章 动态规划part03 正式开始背包问题&#xff0c;背包问题还是挺难的&#xff0c;虽然大家可能看了很多背包问题模板代码&#xff0c;感觉挺简单&#xff0c;但基本理解的都不够深入。 如果是直接从来没听过背包问题&#xff0c;可以先看文字讲解慢慢了解 这是干什么的。 …