-
<sql>
-
<select/>, <insert/>, <update/>, <delete/>
- 这些标签在映射文件中分别用来定义 SQL 查询、插入、更新和删除操作,以及它们的执行逻辑和结果映射:
<select id="getUserById" parameterType="int" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.model.User">
INSERT INTO users(username, password)
VALUES(#{username}, #{password})
</insert>
-
<if>, <choose>, <when>, <otherwise>, <where>, <set>, <foreach>
- 动态 SQL 标签使得 SQL 语句可以根据参数动态构建:
<!-- 使用 if 条件判断 -->
<select id="selectUsersWithConditions" parameterType="map">
SELECT * FROM users as users
<where>
<if test="param.id != null">AND users.id = #{param.id}</if>
<if test="param.userName !=null and param.userName != ''">
AND users.user_name LIKE CONCAT('%',#{param.userName},'%')
</if>
and users.id in
(#{id})
```xml
<!-- 使用 foreach 循环遍历集合参数 -->
<insert id="batchInsertUsers">
INSERT INTO users(username, email)
VALUES
<foreach item="user" index="index" collection="list" open="(" separator="),(" close=")">
#{user.username}, #{user.email}
</foreach>
</insert>
```
```xml
<!-- 使用 choose when 判断 -->
<if test="param.regType !=null and param.regType != ''">
<choose>
<when test="param.regType == 'weixin'">
and users.reg_type = 'weixin'
</when>
<when test="param.regType == 'app'">
and users.reg_type ='app'
</when>
<otherwise>
and users.reg_type = 'other'
</otherwise>
</choose>
</if>
原文链接 https://www.hanyuanhun.cn | https://node.hanyuanhun.cn