MyBatis深度面试指南之三

发布于:2025-06-29 ⋅ 阅读:(23) ⋅ 点赞:(0)

一、XML映射文件进阶标签

1. 核心辅助标签
标签 作用 示例
<resultMap> 自定义结果集映射规则 <resultMap id="userMap" type="User"> <id property="id" column="user_id"/>
<sql> 定义可重用的SQL片段 <sql id="baseColumn">id,name,age</sql>
<include> 引用SQL片段 SELECT <include refid="baseColumn"/> FROM users
<selectKey> 获取非自增主键值 支持order="BEFORE/AFTER"获取序列值
<parameterMap> 参数映射(已废弃,推荐内联参数)
2. 动态SQL九大标签
<!-- 条件分支示例 -->
<select id="findUser">
  SELECT * FROM users
  <where>
    <if test="name != null">
      AND name LIKE CONCAT('%',#{name},'%')
    </if>
    <choose>
      <when test="age != null">AND age = #{age}</when>
      <otherwise>AND status = 1</otherwise>
    </choose>
    <foreach item="id" collection="ids" open="AND id IN (" separator="," close=")">
      #{id}
    </foreach>
  </where>
</select>

作用范围<if>, <choose>/<when>/<otherwise>, <trim>, <where>, <set>, <foreach>, <bind>


二、XML文件ID重复问题

命名空间(namespace)是关键

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

<!-- AdminMapper.xml -->
<mapper namespace="com.example.AdminMapper">
  <select id="selectById">...</select> <!-- 允许相同id -->
</mapper>
  • 无namespace:ID直接作为Map键值,重复导致覆盖
  • 有namespace命名空间+ID构成唯一键(如 com.example.UserMapper.selectById

三、半自动ORM vs 全自动ORM

特性 MyBatis (半自动) Hibernate (全自动)
SQL控制 需手动编写SQL 自动生成HQL
关联查询 需配置<association>/<collection> 对象导航自动加载关联
性能优化 精准控制SQL,避免N+1问题 需解决N+1查询问题
灵活性 支持复杂SQL和存储过程 对复杂SQL支持较弱
核心区别:MyBatis将对象映射自动化,但SQL生成需手动控制

四、