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>
子元素顺序:cache → resultMap → select|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.selectById 与 com.example.mapper.OrderMapper.selectById。
要点总结
<mapper>根元素 namespace 必须与 Mapper 接口全限定名一致- 子元素顺序:cache → resultMap → SQL 语句
- MyBatis 通过 namespace.id 唯一标识 SQL 语句
- namespace 错误会抛出 BindingException
📝 发现内容有误?点击此处直接编辑