MyBatis核心知识解析

5 阅读14分钟

一、MyBatis基础认知

1.1 什么是MyBatis

MyBatis(原iBatis)是一款持久层框架,由Apache软件基金会开发,2010年迁移到Google Code,后更名为MyBatis,2013年又迁移到GitHub。它是一款半ORM(Object Relational Mapping,对象关系映射)框架,核心作用是简化Java程序与数据库的交互,解决JDBC编程的繁琐问题。

MyBatis的核心思想是“将SQL与Java代码分离”,允许开发者手动编写SQL语句,兼顾SQL的灵活性和Java对象的易用性——既不像JDBC那样需要手动编写大量重复的连接、执行、关闭代码,也不像Hibernate那样完全封装SQL(灵活性不足),而是让开发者自主控制SQL,同时将查询结果自动映射为Java对象,实现“SQL语句与Java代码解耦”。

MyBatis是Java后端开发中最主流的持久层框架,常与Spring、Spring Boot框架整合使用,适用于各种规模的Java项目,尤其适合需要灵活控制SQL的场景(如复杂查询、多表关联)。

1.2 MyBatis的核心优势

  • 简化JDBC编程:封装了JDBC的连接、执行、结果集处理、资源关闭等重复操作,开发者只需专注于SQL编写和结果映射。

  • SQL灵活性高:允许开发者手动编写SQL语句,支持复杂查询、多表关联、动态SQL,适配各种复杂业务场景,避免ORM框架的SQL黑盒问题。

  • 低侵入性:无需让Java实体类继承特定接口或继承特定类,只需通过XML或注解配置映射关系,对原有代码影响小。

  • 易于整合:无缝整合Spring、Spring Boot框架,通过简单配置即可实现依赖注入、事务管理,降低项目搭建难度。

  • 轻量级:核心包体积小,配置简单,运行效率高,无需依赖重量级组件,启动速度快。

  • 支持多种数据库:适配MySQL、Oracle、SQL Server等主流数据库,只需修改SQL语句和配置,即可切换数据库。

1.3 MyBatis与JDBC、Hibernate的对比

明确MyBatis的定位,需对比JDBC(原生)和Hibernate(全ORM),理解三者的适用场景:

对比维度JDBC(原生)MyBatis(半ORM)Hibernate(全ORM)
SQL控制手动编写所有SQL,灵活性极高,但重复代码多手动编写SQL,灵活性高,无重复代码自动生成SQL,灵活性低,复杂查询不便
代码量代码繁琐(连接、关闭、结果处理)代码简洁(封装重复操作)代码最少(完全封装)
学习成本低(原生API)中(需掌握配置和映射)高(需掌握ORM思想和复杂配置)
适用场景简单小程序、学习测试中大型项目、需要灵活控制SQL小型项目、SQL简单、无需手动写SQL

1.4 MyBatis核心架构

MyBatis的核心架构分为三层,自上而下分别是:

  1. 接口层(API层):提供给开发者使用的接口,如SqlSession、Mapper接口,开发者通过这些接口操作数据库。

  2. 核心层:MyBatis的核心,负责SQL解析、参数处理、结果映射、缓存管理等,包含SqlSessionFactory、Executor、MappedStatement等核心组件。

  3. 基础层:负责连接管理、事务管理、日志打印等基础功能,支撑核心层运行。

核心组件说明

  • SqlSessionFactory:MyBatis的核心工厂,用于创建SqlSession对象,生命周期是“全局唯一”,通常在项目启动时创建一次。

  • SqlSession:数据库会话对象,用于执行SQL语句、提交/回滚事务,生命周期是“一次请求/一次会话”,用完必须关闭,线程不安全,不能共享。

  • Mapper接口:开发者定义的持久层接口,MyBatis会自动生成接口的实现类(代理类),无需手动编写实现。

  • MappedStatement:封装SQL语句、参数、结果映射等信息,是MyBatis解析SQL的核心对象。

二、MyBatis环境搭建

MyBatis环境搭建分为“纯MyBatis搭建”和“Spring整合MyBatis搭建”,实际开发中以“Spring整合MyBatis”为主,此处先讲解纯MyBatis搭建(理解核心流程),再讲解Spring整合方式(实战常用)。

2.1 纯MyBatis环境搭建

2.1.1 步骤1:导入Maven依赖

在pom.xml中引入MyBatis核心依赖和MySQL驱动依赖(适配MySQL 8.0+):

<dependencies>
    <!-- MyBatis核心依赖 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        &lt;version&gt;3.5.13&lt;/version&gt; <!-- 最新稳定版 -->
    &lt;/dependency&gt;
    
    <!-- MySQL驱动依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33&lt;/version&gt;
    &lt;/dependency&gt;
    
    <!-- 日志依赖(可选,用于打印SQL) -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

2.1.2 步骤2:编写MyBatis核心配置文件(mybatis-config.xml)

核心配置文件用于配置数据库连接、Mapper映射文件路径、全局参数等,放在resources目录下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;
&lt;configuration&gt;
    <!-- 1. 配置环境(可配置多个环境,默认使用指定环境) -->
    <environments default="development">
        <environment id="development">
            <!-- 事务管理器:JDBC事务(MyBatis自带,简单实用) -->
            <transactionManager type="JDBC"/>
            <!-- 数据源:配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_db?useSSL=false&serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

<!-- 2. 配置Mapper映射文件路径(告诉MyBatis去哪里找SQL映射文件) -->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

关键说明:

  • driver:MySQL 8.0+的驱动类是com.mysql.cj.jdbc.Driver,5.0+是com.mysql.jdbc.Driver。

  • url:需添加serverTimezone=UTC(时区配置),避免时区异常;useSSL=false关闭SSL验证。

2.1.3 步骤3:编写实体类(POJO)

实体类与数据库表一一对应,属性名建议与表字段名一致(便于自动映射):

// 数据库表:user(id, username, age, create_time)
public class User {
    private Integer id;
    private String username;
    private Integer age;
    private Date createTime; // 与表字段create_time对应(MyBatis支持下划线转驼峰)

    // 无参构造器(MyBatis反射需要)
    public User() {}

    // 有参构造器(可选)
    public User(String username, Integer age) {
        this.username = username;
        this.age = age;
    }

    // getter/setter方法(必须有,MyBatis通过setter赋值)
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
    public Date getCreateTime() { return createTime; }
    public void setCreateTime(Date createTime) { this.createTime = createTime; }
}

2.1.4 步骤4:编写Mapper接口和映射文件

Mapper接口是持久层接口,映射文件用于编写SQL语句和结果映射,二者需保持“同名同路径”(约定优于配置)。

1. Mapper接口(UserMapper.java)
// 包路径:com.example.mybatis.mapper
public interface UserMapper {
    // 根据id查询用户(方法名与映射文件中SQL的id一致)
    User selectUserById(Integer id);
    
    // 新增用户
    int insertUser(User user);
}
2. 映射文件(UserMapper.xml)

放在resources/mapper目录下,与Mapper接口对应:

<?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"&gt;
<!-- namespace:对应Mapper接口的全限定名,必须一致 -->
<mapper namespace="com.example.mybatis.mapper.UserMapper"><!-- 1. 根据id查询用户 -->
    <select id="selectUserById" parameterType="java.lang.Integer" resultType="com.example.mybatis.pojo.User">
        select id, username, age, create_time as createTime from user where id = #{id}
    &lt;/select&gt;

    <!-- 2. 新增用户 -->
    <insert id="insertUser" parameterType="com.example.mybatis.pojo.User">
        insert into user (username, age, create_time) values (#{username}, #{age}, now())
    </insert>
</mapper>

关键说明:

  • namespace:必须是Mapper接口的全限定名,MyBatis通过该属性关联接口和映射文件。

  • id:SQL语句的唯一标识,必须与Mapper接口的方法名一致。

  • parameterType:传入SQL的参数类型(可省略,MyBatis会自动推断)。

  • resultType:SQL查询结果的返回类型(实体类全限定名),MyBatis会自动将结果映射为实体对象。

  • #{ }:参数占位符,相当于JDBC的?,自动防止SQL注入,推荐使用。

2.1.5 步骤5:编写测试类(验证环境)

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 MyBatisTest {
    public static void main(String[] args) throws IOException {
        // 1. 读取核心配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        
        // 2. 创建SqlSessionFactory(全局唯一)
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        
        // 3. 创建SqlSession(一次会话,用完关闭)
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        // 4. 获取Mapper接口代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        
        // 5. 执行SQL操作
        // 5.1 查询用户
        User user = userMapper.selectUserById(1);
        System.out.println("查询到的用户:" + user);
        
        // 5.2 新增用户(MyBatis默认不自动提交事务,需手动提交)
        User newUser = new User("zhangsan", 20);
        int rows = userMapper.insertUser(newUser);
        sqlSession.commit(); // 提交事务
        System.out.println("新增用户影响行数:" + rows);
        
        // 6. 关闭SqlSession
        sqlSession.close();
    }
}

注意:MyBatis默认不自动提交事务,执行新增、修改、删除操作后,必须调用sqlSession.commit()提交事务,否则操作不会生效。

2.2 Spring整合MyBatis

实际开发中,通常会整合Spring框架,由Spring管理SqlSessionFactory、SqlSession、Mapper接口等对象,无需手动创建和关闭,同时结合Spring的事务管理,简化开发。

2.2.1 步骤1:导入整合依赖

<dependencies><!-- Spring核心依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.20&lt;/version&gt;
    &lt;/dependency&gt;
    <!-- Spring JDBC依赖(整合MyBatis需要) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.20</version>
    </dependency>
   <!-- MyBatis核心依赖 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <!-- Spring整合MyBatis依赖(核心整合包) -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.1.0</version&gt;
    &lt;/dependency&gt;
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version&gt;
    &lt;/dependency&gt;
    <!-- 连接池(Druid,推荐) -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.16</version>
    </dependency>
</dependencies>

2.2.2 步骤2:编写Spring配置文件(applicationContext.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd"&gt;

    <!-- 1. 加载数据库配置文件可选推荐-->
    <context:property-placeholder location="classpath:db.properties"/&gt;

    <!-- 2. 配置数据源Druid连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/&gt;
    &lt;/bean&gt;

    <!-- 3. 配置SqlSessionFactory由Spring管理-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBatis核心配置文件路径 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 配置Mapper映射文件路径(可选,也可在mybatis-config.xml中配置) -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean><!-- 4. 配置Mapper接口扫描(自动生成代理对象,注入Spring容器) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描Mapper接口所在的包 -->
        <property name="basePackage" value="com.example.mybatis.mapper"/&gt;
    &lt;/bean&gt;

    <!-- 5. 配置事务管理器Spring事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    &lt;/bean&gt;

    <!-- 开启注解式事务(可选,推荐) -->
    <context:annotation-config/>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

2.2.3 步骤3:编写数据库配置文件(db.properties)

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis_db?useSSL=false&serverTimezone=UTC
db.username=root
db.password=123456

2.2.4 步骤4:测试整合效果

此时,Mapper接口会被Spring自动扫描并生成代理对象,可通过@Autowired直接注入使用,无需手动创建SqlSession:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringMyBatisTest {
    public static void main(String[] args) {
        // 1. 初始化Spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        // 2. 注入Mapper接口(Spring自动生成代理对象)
        UserMapper userMapper = context.getBean(UserMapper.class);
        
        // 3. 执行SQL操作(事务由Spring管理,新增/修改/删除自动提交)
        User user = userMapper.selectUserById(1);
        System.out.println("查询到的用户:" + user);
    }
}

三、MyBatis核心:Mapper映射(重点)

Mapper映射是MyBatis的核心,负责将SQL语句的参数和结果与Java对象关联,分为“参数映射”和“结果映射”,支持XML配置和注解两种方式,实际开发中以XML配置为主(灵活性高)。

3.1 参数映射(传入SQL的参数处理)

参数映射是指将Java方法的参数,传递到SQL语句中,MyBatis支持多种参数类型,核心是使用#{ }或${ }占位符。

3.1.1 两种占位符对比(必记)

占位符核心特点是否防止SQL注入适用场景
#{ }预编译占位符,相当于JDBC的?,自动处理参数类型转换是(推荐使用)普通参数传递(如查询、新增、修改)
${ }字符串拼接,直接将参数拼接到SQL中,不做类型转换否(存在SQL注入风险)动态表名、动态排序字段(如order by ${field})

示例(${ }的使用,谨慎使用):

<!-- 动态表名查询,表名由参数传入 -->
<select id="selectByTableName" parameterType="String" resultType="com.example.mybatis.pojo.User">
    select * from ${tableName} where id = #{id}
</select>

3.1.2 常见参数类型的映射

1. 单个参数

单个参数(如Integer、String),#{ }中可任意填写名称(无需与方法参数名一致):

// Mapper接口
User selectUserById(Integer id);

// 映射文件
<select id="selectUserById" parameterType="Integer" resultType="User">
    select * from user where id = #{任意名称}
</select>
2. 多个参数(@Param注解)

多个参数时,需使用@Param注解指定参数名称,#{ }中填写注解指定的名称:

// Mapper接口
User selectUserByUsernameAndAge(@Param("username") String username, @Param("age") Integer age);

// 映射文件
<select id="selectUserByUsernameAndAge" resultType="User">
    select * from user where username = #{username} and age = #{age}
</select>
3. 实体类参数

参数是实体类时,#{ }中填写实体类的属性名(需与getter/setter方法对应):

// Mapper接口
int insertUser(User user);

// 映射文件
<insert id="insertUser" parameterType="User">
    insert into user (username, age) values (#{username}, #{age})
</insert>
4. Map参数

参数是Map时,#{ }中填写Map的key值:

// Mapper接口
User selectUserByMap(Map<String, Object> map);

// 映射文件
<select id="selectUserByMap" parameterType="Map" resultType="User">
    select * from user where username = #{username} and age = #{age}
</select>

// 测试时传入Map
Map<String, Object&gt; map = new HashMap<>();
map.put("username", "zhangsan");
map.put("age", 20);
userMapper.selectUserByMap(map);

3.2 结果映射(SQL结果与Java对象关联)

结果映射是指将SQL查询的结果集,自动映射为Java实体类对象,MyBatis支持两种方式:自动映射和手动映射(resultMap)。

3.2.1 自动映射(默认开启)

当实体类属性名与数据库表字段名完全一致,或满足“下划线转驼峰”规则时,MyBatis会自动将结果映射为实体对象,无需额外配置。

下划线转驼峰配置(在mybatis-config.xml中添加):

&lt;configuration&gt;
    <!-- 开启下划线转驼峰(默认不开启,推荐开启) -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/&gt;
    &lt;/settings&gt;
    
    <!-- 其他配置环境mappers-->
</configuration>

示例:表字段create_time,实体类属性createTime,开启下划线转驼峰后,MyBatis会自动映射。

3.2.2 手动映射(resultMap,重点)

当实体类属性名与表字段名不一致,且不满足下划线转驼峰规则时,需使用resultMap手动配置映射关系,这是实际开发中常用的方式。

<!-- 定义resultMap,id是唯一标识,type是实体类全限定名 -->
<resultMap id="userResultMap" type="com.example.mybatis.pojo.User"&gt;
    <!-- 主键映射id标签 -->
    <id column="user_id" property="id"/&gt;
    <!-- 普通字段映射result标签 -->
    <result column="user_name" property="username"/>
    <result column="user_age" property="age"/>
    <result column="create_time" property="createTime"/&gt;
&lt;/resultMap&gt;

<!-- 查询时使用resultMap指定映射关系替代resultType -->
<select id="selectUserById" parameterType="Integer" resultMap="userResultMap">
    select user_id, user_name, user_age, create_time from user where user_id = #{id}
</select>

说明:column是数据库表字段名,property是实体类属性名,一一对应即可。

3.3 Mapper注解方式

除了XML配置,MyBatis还支持通过注解编写SQL,无需映射文件,适合简单SQL场景,复杂SQL仍推荐XML配置。

public interface UserMapper {
    // @Select注解编写查询SQL
    @Select("select * from user where id = #{id}")
    User selectUserById(Integer id);
    
    // @Insert注解编写新增SQL
    @Insert("insert into user (username, age) values (#{username}, #{age})")
    int insertUser(User user);
    
    // @Update注解编写修改SQL
    @Update("update user set username = #{username} where id = #{id}")
    int updateUser(User user);
    
    // @Delete注解编写删除SQL
    @Delete("delete from user where id = #{id}")
    int deleteUser(Integer id);
}

四、MyBatis核心:动态SQL

动态SQL是MyBatis的强大特性之一,允许根据不同的参数条件,动态生成不同的SQL语句,避免编写大量重复的SQL,适配复杂的查询场景(如多条件查询、模糊查询)。

MyBatis提供7个核心动态SQL标签,重点掌握前5个,灵活组合使用即可满足大部分场景。

4.1 常用动态SQL标签解析

4.1.1 if标签(条件判断)

最常用标签,根据参数是否为空,动态拼接SQL片段,常用于多条件查询。

<select id="selectUserByCondition" parameterType="User" resultType="User">
    select * from user where 1=1
    <!-- 如果username不为空,拼接username查询条件 -->
    <if test="username != null and username != ''">
        and username like concat('%', #{username}, '%')
    &lt;/if&gt;
    <!-- 如果age不为空,拼接age查询条件 -->
    <if test="age != null">
        and age = #{age}
    </if>
</select>

注意:where后面加1=1,是为了避免当第一个if条件不成立时,SQL出现“where and”的语法错误。

4.1.2 where标签(替代where关键字)

自动处理SQL中的and/or关键字,避免“where and”语法错误,可替代上面的1=1写法。

<select id="selectUserByCondition" parameterType="User" resultType="User">
    select * from user
    <where>
        <if test="username != null and username != ''">
            and username like concat('%', #{username}, '%')
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
    </where>
</select>

说明:如果所有if条件都不成立,&lt;where&gt;标签会自动省略,不会生成where关键字,避免SQL错误。

4.1.3 foreach标签(循环遍历)

用于循环遍历集合(List、Array、Map),常用于in查询、批量新增、批量删除等场景。

示例1:in查询(遍历List集合)
// Mapper接口
List<User> selectUserByIds(@Param("ids") List<Integer> ids);

// 映射文件
<select id="selectUserByIds" parameterType="List" resultType="User">
    select * from user
    <where>
        id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </where>
</select>

标签属性说明:

  • collection:集合参数的名称(如果用@Param注解,填写注解名称;如果是List,默认是list;如果是Array,默认是array)。

  • item:循环中每个元素的别名。

  • open:循环开始的符号(如in查询的左括号)。

  • close:循环结束的符号(如in查询的右括号)。

  • separator:循环元素之间的分隔符(如逗号)。

示例2:批量新增
<insert id="batchInsertUser" parameterType="List">
    insert into user (username, age) values
    <foreach collection="list" item="user" separator=",">
        (#{user.username}, #{user.age})
    </foreach>
</insert>

4.1.4 set标签(用于修改操作)

自动处理修改SQL中的逗号,避免“set ,”的语法错误,适用于动态修改场景(只修改不为空的字段)。

<update id="updateUser" parameterType="User">
    update user
    <set>
        <if test="username != null and username != ''">
            username = #{username},
        </if>
        <if test="age != null">
            age = #{age},
        </if>
    </set>
    where id = #{id}
</update>

五、MyBatis分页查询

分页查询是日常开发中必备的功能,MyBatis本身不提供分页功能,需结合第三方插件(PageHelper)实现,PageHelper是MyBatis最常用的分页插件,配置简单、使用便捷。

5.1 分页插件使用步骤(Spring整合场景)

步骤1:导入PageHelper依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.3.2</version>
</dependency>

步骤2:配置分页插件(在Spring配置文件中)

<!-- 配置SqlSessionFactory时,添加分页插件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:mapper/*.xml"/&gt;
    <!-- 配置分页插件 -->
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    &lt;value&gt;
                        <!-- 配置数据库方言(MySQL) -->
                        helperDialect=mysql
                        <!-- 开启合理化分页(避免页码超出范围) -->
                        reasonable=true
                    </value>
                </property>
            </bean>
        </array>
    </property>
</bean>

步骤3:使用分页插件(代码层面)

// Mapper接口(无需修改,正常编写查询SQL)
List<User> selectAllUser();

// 测试/Service层使用分页
public PageInfo<User> selectUserByPage(Integer pageNum, Integer pageSize) {
    // 1. 开启分页(pageNum:当前页码,pageSize:每页条数)
    PageHelper.startPage(pageNum, pageSize);
    
    // 2. 执行查询(无需修改SQL,PageHelper自动拦截并添加分页语句)
    List<User> userList = userMapper.selectAllUser();
    
    // 3. 封装分页结果(PageInfo包含分页详细信息)
    PageInfo&lt;User&gt; pageInfo = new PageInfo<>(userList);
    return pageInfo;
}

步骤4:分页结果说明(PageInfo核心属性)

  • pageNum:当前页码

  • pageSize:每页条数

  • total:总记录数

  • pages:总页数

  • list:当前页的数据列表

  • hasNextPage:是否有下一页

  • hasPreviousPage:是否有上一页