mybait的动态sql
时间: 2023-09-10 12:08:41 浏览: 77
MyBatis的动态SQL是指在Mapper.xml文件中根据条件拼接SQL语句的过程。MyBatis提供了以下标签来实现动态SQL:
1. if
if标签可以根据条件来判断是否拼接SQL语句,语法如下:
```xml
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM users
WHERE 1=1
<if test="id != null">
AND id = #{id}
</if>
<if test="username != null">
AND username like #{username}
</if>
</select>
```
2. choose, when, otherwise
choose标签类似于Java中的switch语句,用来根据不同的条件选择不同的SQL语句,语法如下:
```xml
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM users
WHERE 1=1
<choose>
<when test="id != null">
AND id = #{id}
</when>
<when test="username != null">
AND username like #{username}
</when>
<otherwise>
AND status = 'ACTIVE'
</otherwise>
</choose>
</select>
```
3. where
where标签可以自动去掉WHERE关键字的前缀,并根据条件拼接WHERE子句,语法如下:
```xml
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM users
<where>
<if test="id != null">
AND id = #{id}
</if>
<if test="username != null">
AND username like #{username}
</if>
</where>
</select>
```
4. set
set标签用于更新操作,可以根据条件拼接SET子句,语法如下:
```xml
<update id="updateUser" parameterType="User">
UPDATE users
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="email != null">
email = #{email},
</if>
</set>
WHERE id = #{id}
</update>
```
5. foreach
foreach标签用于遍历集合或数组,并根据遍历结果拼接SQL语句,语法如下:
```xml
<select id="selectUsers" parameterType="map" resultType="User">
SELECT * FROM users
WHERE id IN
<foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
#{item}
</foreach>
</select>
```
以上就是MyBatis中常用的动态SQL标签。通过这些标签,我们可以根据不同的条件拼接出不同的SQL语句,从而实现更加灵活和可复用的SQL编写方式。
阅读全文