动态sql的标签<if>、<where>、<set>、<trim>、<foreach>给我举个例子
时间: 2023-08-06 12:06:48 浏览: 113
MyBatis动态SQL标签用法实例详解
当使用MyBatis进行动态SQL的编写时,通常会使用以下标签:
1. <if>标签:用于判断条件是否成立,如果成立则执行内部的SQL语句,否则忽略。
```
<select id="getUserList" resultType="User">
SELECT * FROM user
WHERE 1=1
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</select>
```
2. <where>标签:用于拼接WHERE子句,如果内部有任何一个条件成立,则WHERE子句会自动添加到SQL语句中。
```
<select id="getUserList" resultType="User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
```
3. <set>标签:用于拼接SET子句,用于更新表中的数据。
```
<update id="updateUser" parameterType="User">
UPDATE user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
WHERE id = #{id}
</update>
```
4. <trim>标签:用于去除SQL语句中的逗号或AND/OR等无用的字符。
```
<select id="getUserList" resultType="User">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</trim>
</select>
```
5. <foreach>标签:用于循环遍历集合或数组,并将其作为参数传递给SQL语句中。
```
<select id="getUserListByIdList" resultType="User">
SELECT * FROM user
WHERE id IN
<foreach collection="idList" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
```
阅读全文