Mybatis XML 映射文件详解
TIP
XML 映射文件是 MyBatis 的核心,定义了 SQL 语句、参数映射和结果映射。
基本结构
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>结果映射
xml
<!-- 基础结果映射 -->
<resultMap id="userMap" type="com.example.entity.User">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="age" property="age"/>
<result column="email" property="email"/>
<result column="created_at" property="createdAt"/>
</resultMap>
<!-- 关联查询映射 -->
<resultMap id="userOrderMap" type="com.example.entity.User" extends="userMap">
<collection property="orders" ofType="com.example.entity.Order">
<id column="order_id" property="id"/>
<result column="order_no" property="orderNo"/>
<result column="amount" property="amount"/>
</collection>
</resultMap>
<select id="selectUserWithOrders" resultMap="userOrderMap">
SELECT u.*, o.id as order_id, o.order_no, o.amount
FROM user u
LEFT JOIN `order` o ON u.id = o.user_id
WHERE u.id = #{id}
</select>一对一和一对多
sql
<!-- 一对一关联 -->
<association property="profile" column="id"
select="com.example.mapper.ProfileMapper.selectByUserId"/>
<!-- 一对多关联 -->
<collection property="orders" column="id"
select="com.example.mapper.OrderMapper.selectByUserId"/>参数传递
xml
<!-- 单个参数 -->
<select id="selectById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<!-- 多个参数 -->
<select id="selectByNameAndAge" resultType="User">
SELECT * FROM user WHERE name = #{name} AND age = #{age}
</select>
<!-- 使用 @Param 注解 -->
<select id="selectByCondition" resultType="User">
SELECT * FROM user
WHERE name = #{name}
<if test="age != null">
AND age = #{age}
</if>
</select>主键回填
xml
<!-- 插入后返回自增主键 -->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})
</insert>