mybatis 动态拼接sql
时间: 2023-07-19 10:29:24 浏览: 85
MyBatis提供了动态SQL的支持,可以根据不同的条件生成不同的SQL语句,具体实现方式有以下几种:
1. if标签
```xml
<select id="getUser" resultType="User">
select * from user where 1=1
<if test="userName != null">
and user_name = #{userName}
</if>
<if test="gender != null">
and gender = #{gender}
</if>
</select>
```
2. choose/when/otherwise标签
```xml
<select id="getUser" resultType="User">
select * from user where 1=1
<choose>
<when test="userName != null">
and user_name = #{userName}
</when>
<when test="gender != null">
and gender = #{gender}
</when>
<otherwise>
and age > 18
</otherwise>
</choose>
</select>
```
3. where标签
```xml
<select id="getUser" resultType="User">
select * from user
<where>
<if test="userName != null">
and user_name = #{userName}
</if>
<if test="gender != null">
and gender = #{gender}
</if>
</where>
</select>
```
4. set标签(用于更新操作)
```xml
<update id="updateUser" parameterType="User">
update user
<set>
<if test="userName != null">
user_name = #{userName},
</if>
<if test="gender != null">
gender = #{gender},
</if>
</set>
where id = #{id}
</update>
```
以上是MyBatis动态SQL的常见实现方式,可以根据实际情况选择使用。
阅读全文