全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 6 分钟 ✍️ juanwangdev

mapper 根元素

XML 映射文件以 <mapper> 为根元素,下面是其核心配置与规则。

namespace 命名空间

XML
<?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">
    <!-- SQL 语句定义 -->
</mapper>

namespace 必须与 Mapper 接口全限定名一致,用于绑定接口与 XML 映射关系。

注意:namespace 错误会导致 MyBatis 无法找到对应的 Mapper 接口,抛出 BindingException

根元素属性与子元素顺序

XML
<mapper namespace="com.example.mapper.UserMapper">
    <!-- 1. 缓存配置(可选) -->
    <cache/>
    
    <!-- 2. resultMap 结果映射 -->
    <resultMap id="BaseResultMap" type="com.example.entity.User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
    </resultMap>
    
    <!-- 3. SQL 语句定义 -->
    <select id="selectById" resultMap="BaseResultMap">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

子元素顺序:cacheresultMapselect|insert|update|delete

namespace 隔离原理

不同 namespace 中的 statement id 可以重复,MyBatis 通过 namespace.id 唯一标识 SQL 语句:

XML
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
    <select id="selectById">...</select>
</mapper>

<!-- OrderMapper.xml -->
<mapper namespace="com.example.mapper.OrderMapper">
    <select id="selectById">...</select>
</mapper>

实际完整 ID 为 com.example.mapper.UserMapper.selectByIdcom.example.mapper.OrderMapper.selectById

要点总结

  • <mapper> 根元素 namespace 必须与 Mapper 接口全限定名一致
  • 子元素顺序:cache → resultMap → SQL 语句
  • MyBatis 通过 namespace.id 唯一标识 SQL 语句
  • namespace 错误会抛出 BindingException

📝 发现内容有误?点击此处直接编辑

← 上一篇 insert 插入语句
下一篇 → select 查询语句
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库