index.md 跨平台编程框架融码智汇 search
跨平台编程知识聚合站EDITOR · 跨平台编程笔记
</> 跨平台编程知识聚合站 Cross-Platform Dev
#893457 框架 2026.12.06 —

Java项目里用MyBatis总是被SQL映射搞晕 从XML配置到Spring整合 手把手带你把动态查询和分页写明白

DIR
框架
COMMIT
893457
DATE
12.06
UPDATE
12.06

MyBatis 的 SQL 映射,说白了就干一件事:把 Java 接口里的一个方法,绑定到 XML 里的一条 SQL 语句上,方法执行时 MyBatis 自动帮你拼装参数、运行 SQL、把结果转成 Java 对象。大多数人被搞晕,不是框架难,而是三件事没串起来:参数怎么传进 SQL、动态标签什么时候生效、分页到底在哪一层做。这篇文章按“XML 配置 → 动态查询 → 分页 → Spring 整合”的顺序,把每一环都写成能直接复制运行的代码,照着走完一遍,SQL 映射的套路基本就通了。

MyBatis 的 SQL 映射到底映射的是什么

SQL 映射是指开发者把 SQL 语句写在 XML 文件(或注解)里,并声明它对应哪个接口的哪个方法,MyBatis 在运行时负责把方法参数填进 SQL、执行后把结果集映射成 POJO。SQL 映射的核心约定只有一条:XML 里 select 标签的 id,必须和 mapper 接口的方法名完全一致;XML 的 namespace,必须是该接口的全限定名。 这两个对不上,MyBatis 启动或调用时就会报 BindingException,这也是一半“搞晕”问题的根源。

一个典型的目录结构长这样:

src/main/java/com/example
├── entity/User.java
└── mapper/UserMapper.java      ← 接口
src/main/resources
└── mapper/UserMapper.xml       ← 对应的 SQL 映射文件

实体类先备好:

package com.example.entity;

public class User {
    private Long id;
    private String username;
    private Integer age;
    private String city;
    // Getter / Setter 省略,写代码时记得生成
}

手把手:第一个 XML 映射文件怎么写

先看 MyBatis 自己的全局配置文件 mybatis.xml,它负责数据源和 mapper 的注册(纯 MyBatis 项目需要它,Spring Boot 项目里这步会被自动托管,但看懂它对理解整合很有帮助):

<?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">
<configuration>
    <properties resource="jdbc.properties"/>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="POOLED"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

接着是 mapper 接口,只声明方法,不写实现:

package com.example.mapper;

import com.example.entity.User;
import java.util.List;

public interface UserMapper {
    List<User> findByCondition(User query);   // 动态查询,后面细讲
    List<User> findByIds(List<Long> ids);     // IN 批量查询
    long countByCondition(User query);        // 动态查询的总数(分页要用)
}

对应的 UserMapper.xml,namespace 写接口的全限定名:

<?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 -->
    <resultMap id="userMap" type="com.example.entity.User">
        <id     property="id"       column="id"/>
        <result property="username" column="username"/>
        <result property="age"      column="age"/>
        <result property="city"     column="city"/>
    </resultMap>

    <!-- 抽公共字段,避免每条 SQL 里重复写列名 -->
    <sql id="baseColumns">id, username, age, city</sql>

    <select id="findByCondition" parameterType="com.example.entity.User" resultMap="userMap">
        select <include refid="baseColumns"/> from t_user
        <where>
            <if test="username != null and username != ''">
                and username like concat('%', #{username}, '%')
            </if>
            <if test="age != null">
                and age &gt;= #{age}
            </if>
            <if test="city != null and city != ''">
                and city = #{city}
            </if>
        </where>
        order by id desc
    </select>

    <select id="findByIds" resultMap="userMap">
        select <include refid="baseColumns"/> from t_user
        where id in
        <foreach collection="list" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>

    <select id="countByCondition" parameterType="com.example.entity.User" resultType="long">
        select count(*) from t_user
        <where>
            <!-- 条件与 findByCondition 完全一致,分页总数才准 -->
            <if test="username != null and username != ''">
                and username like concat('%', #{username}, '%')
            </if>
            <if test="age != null">
                and age &gt;= #{age}
            </if>
            <if test="city != null and city != ''">
                and city = #{city}
            </if>
        </where>
    </select>
</mapper>

这段 XML 里有两个新手必踩的坑,先给你标出来:第一,&gt;= 是 >= 在 XML 里的转义写法,直接写 >= 会导致 XML 解析报错;第二,#{xxx} 是预编译占位符(相当于 PreparedStatement 的 ?),能防 SQL 注入,而 ${xxx} 是字符串直接拼接,只有表名、排序字段这类无法预编译的场景才允许用 ${},传用户输入永远用 #{}。

动态查询:if、where、choose、foreach 一次讲透

动态查询是指根据传入参数是否为空,自动决定 SQL 里哪些条件生效,MyBatis 靠 <if>、<where>、<choose>、<foreach> 这几个标签实现。上面 findByCondition 已经展示了最常用的组合:<where> 标签会自动处理两个细节——条件全部为空时它什么都不输出,且自动把第一个条件的 and 去掉,省得你手动判断。

<choose> 适合“只走其中一个分支”的场景,比如按 id 查就别按用户名查:

<select id="findSmart" resultMap="userMap">
    select <include refid="baseColumns"/> from t_user
    <where>
        <choose>
            <when test="id != null">
                and id = #{id}
            </when>
            <otherwise>
                and username like concat('%', #{username}, '%')
            </otherwise>
        </choose>
    </where>
</select>

几个实战中反复用到的判断技巧:test="username != null and username != ''" 用来同时排除 null 和空串;数字类型只判 test="age != null" 即可;判空字符串还可以用 OGNL 写法 test='username != null and username.length() > 0'。另外注意,MyBatis 的 test 里属性名区分大小写,写成 test="Age != null" 是匹配不到的。

<foreach> 除了上面 IN 查询的用法,还常用于批量插入:

<insert id="batchInsert">
    insert into t_user (username, age, city) values
    <foreach collection="list" item="u" separator=",">
        (#{u.username}, #{u.age}, #{u.city})
    </foreach>
</insert>

调用时 mapper.batchInsert(userList) 即可。如果方法参数只有一个 List 且没加 @Param,foreach 里的 collection 写 list 就行;一旦方法有多个参数,就必须用 @Param("xxx") 命名,foreach 的 collection 也要跟着改成对应的名字。

分页两种主流写法,坑都给你标出来

分页在 MyBatis 里有两条路:物理分页(SQL 里 LIMIT,只取当页数据)和内存分页(把全表查出来再切分)。MyBatis 自带的 RowBounds 是内存分页,只适合百万行以内的小表,数据量大时会把数据库拖垮,生产环境别用。 生产上要么用 PageHelper 这类插件,要么自己写 limit。

先说手写 limit 的方式,思路是“查总数 + 查当页”两条 SQL:

// Service 层示例
int pageNo = 2;      // 第几页
int pageSize = 10;   // 每页几条

long total = userMapper.countByCondition(query);          // 先查总数
int offset = (pageNo - 1) * pageSize;                      // 计算偏移量
List<User> users = userMapper.findPage(query, offset, pageSize); // 再查当页

int totalPages = (int) ((total + pageSize - 1) / pageSize); // 向上取整算总页数

对应的 XML:

<select id="findPage" resultMap="userMap">
    select <include refid="baseColumns"/> from t_user
    <where>
        <!-- 与 countByCondition 条件保持一致 -->
        <if test="username != null and username != ''">
            and username like concat('%', #{username}, '%')
        </if>
    </where>
    order by id
    limit #{offset}, #{limit}
</select>

手写的好处是逻辑完全可控、SQL 走向清晰;缺点是每加一种查询就要维护两份条件(查询和 count),容易改漏。PageHelper 的做法正好反过来:它在 SQL 外层自动拼上 limit 和 count,你只管正常写查询:

PageHelper.startPage(2, 10);                        // 紧挨着查询语句调用
List<User> users = userMapper.findByCondition(query);
PageInfo<User> pageInfo = new PageInfo<>(users);    // 总条数、总页数都在这里

两种方式的对比:

方案 优点 缺点 适用场景
手写 limit 可控、可针对性优化 count 条件要维护两份 查询逻辑复杂、对 SQL 有精细要求
PageHelper 零侵入、代码少 ThreadLocal 有清理风险,复杂 SQL 自动 count 可能不准 常规 CRUD、分页需求多

用 PageHelper 有两个必须记住的点:startPage 必须紧贴在目标查询之前调用,中间隔了别的查询就分页错位;PageHelper 靠 ThreadLocal 传分页参数,用完会自动清理,但在事务里跨方法分页时要格外小心。

Spring Boot 整合 MyBatis:五步搞定

Spring Boot 项目里,MyBatis 的配置从独立的 XML 迁移到了 application.yml,数据源、连接池、mapper 位置都由 starter 自动装配,步骤压缩成五步:

第一步,pom 里加依赖(Spring Boot 3.x 用 starter 3.0.x):

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

第二步,application.yml 里写 MyBatis 相关配置:

mybatis:
  mapper-locations: classpath:mapper/*.xml   # XML 文件位置
  type-aliases-package: com.example.entity   # 实体包,XML 里可直接写 User
  configuration:
    map-underscore-to-camel-case: true       # city_name 自动映射 city

第三步,启动类上扫 mapper 包:

@SpringBootApplication
@MapperScan("com.example.mapper")   // 替代逐个写 @Mapper
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

第四步,把前面写好的 UserMapper.xml 放进 resources/mapper/ 目录。

第五步,像普通 Spring Bean 一样注入 mapper 使用:

@Service
public class UserService {
    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {  // 构造器注入,推荐
        this.userMapper = userMapper;
    }

    public List<User> search(User query, int page, int size) {
        PageHelper.startPage(page, size);
        return userMapper.findByCondition(query);
    }
}

整合之后,map-underscore-to-camel-case: true 会把下划线列名自动映射到驼峰属性,像上面这种“列名和属性名只差大小写格式”的简单映射,连 resultMap 都可以省掉;但只要出现 is_deleted_flag → deleted 这类不一致,就还是得老老实实写 resultMap。

常见问题

#{} 和 ${} 到底用哪个?

默认全部用 #{},它会被翻译成预编译占位符 ?,防 SQL 注入。只有表名动态切换、ORDER BY ${column} 这类没法预编译、又必须拼进 SQL 的场景才用 ${},且必须对取值做白名单校验,绝不能直接接收前端输入。

XML 映射和注解(@Select)怎么选?

SQL 简单(两三行、少条件)用 @Select 注解写,代码集中、改动快;SQL 复杂、带动态标签或批量操作用 XML,因为动态 SQL 写在注解里可读性极差。同一个项目里混用完全没问题,建议按 SQL 复杂度二选一。

MyBatis、MyBatis-Plus 要不要直接上 MyBatis-Plus?

MyBatis-Plus 在 MyBatis 之上封装了通用 Mapper,单表 CRUD、分页不用写 SQL,适合后台管理系统这类以单表查询为主的项目;如果业务 SQL 复杂、多表联查占比高,原生 MyBatis 的可控性更好。两者底层兼容,学会原生 MyBatis 再切 MyBatis-Plus 基本零成本。

mapper 接口方法名和 XML 的 id 对不上会怎样?

启动时若开启了 mapper 校验会直接报 Invalid bound statement;没校验的话则运行时报同样的错——这是 MyBatis 最常见的报错,排查时先核对 namespace 全限定名和 id 是否逐字一致,再确认 XML 文件被 mapper-locations 扫到了。

分页总数 count 查询能省吗?

不能。总页数、前端页码控件都依赖总数,省掉 count 只能取当页数据,会导致“最后一页判断”失真。PageHelper 默认会补一条 count SQL,性能敏感的场景可以用 countColumn 或手动写精简的 count 语句来优化,但总数本身不能丢。

从 XML 配置到 Spring 整合,再到动态查询和分页,把这四块串起来之后你会发现 MyBatis 的套路其实很固定:接口定契约、XML 写 SQL、标签做动态、插件管分页。建议把文中 UserMapper 的例子在自己的项目里跑一遍,遇到报错对照“常见问题”逐条排查,两三个小时后这套流程就能形成肌肉记忆。

//

同目录笔记

Same Dir