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

快速上手mybatis教程

基础知识

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.lryc.cn/news/530837.html

相关文章:

  • 本地部署DeepSeek-R1保姆级教程
  • blender 相机参数
  • 在GPIO控制器中,配置通用输入,读取IO口电平时,上拉和下拉起到什么作用
  • Maven工程核心概念GAVP详解:从命名规范到项目协作的基石
  • 如何利用DeepSeek打造医疗领域专属AI助手?从微调到部署全流程解析
  • Redis|前言
  • 眼见着折叠手机面临崩溃,三星计划增强抗摔能力挽救它
  • Leetcode面试高频题分类刷题总结
  • Vue.js `v-memo` 性能优化技巧
  • Altium Designer绘制原理图时画斜线的方法
  • 在K8S中,有哪几种控制器类型?
  • 什么是Rust?它有什么特点?为什么要学习Rust?
  • Golang 并发机制-3:通道(channels)机制详解
  • kamailio的kamctl的使用
  • HarmonyOS:ArkWeb进程
  • UI线程用到COM只能选单线程模型
  • LLMs之DeepSeek:Math-To-Manim的简介(包括DeepSeek R1-Zero的详解)、安装和使用方法、案例应用之详细攻略
  • 在C语言中使用条件变量实现线程同步
  • 图书管理系统 Axios 源码__新增图书
  • Maven全解析:从基础到精通的实战指南
  • 数据密码解锁之DeepSeek 和其他 AI 大模型对比的神秘面纱
  • python算法和数据结构刷题[5]:动态规划
  • Ollama+OpenWebUI部署本地大模型
  • Python从0到100(八十六):神经网络-ShuffleNet通道混合轻量级网络的深入介绍
  • 【网络】传输层协议TCP(重点)
  • 海思ISP开发说明
  • 实验十 Servlet(一)
  • doris:聚合模型的导入更新
  • Java NIO_非阻塞I/O的实现与优化
  • 代码随想录算法训练营Day51 | 101.孤岛的总面积、102.沉没孤岛、103.水流问题、104.建造最大岛屿