如何使用mybatis动态sql
时间: 2023-08-14 08:05:46 浏览: 46
Mybatis动态SQL是一种灵活的机制,它允许在运行时根据不同的条件生成不同的SQL语句。以下是使用Mybatis动态SQL的一些常见方法:
1. if元素:可以在SQL语句中根据不同的条件添加或排除一些SQL语句片段。例如:
```
<select id="findUsers" parameterType="map" resultMap="userResultMap">
SELECT * FROM users
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
```
这个SQL语句中的if元素根据传入的参数map中的name和age是否为null,决定是否添加AND name = #{name}和AND age = #{age}到SQL语句中。
2. choose、when和otherwise元素:可以使用choose、when和otherwise元素来实现类似于Java中的switch语句的功能,根据不同的条件生成不同的SQL语句。例如:
```
<select id="findUsers" parameterType="map" resultMap="userResultMap">
SELECT * FROM users
<where>
<choose>
<when test="name != null">
AND name = #{name}
</when>
<when test="age != null">
AND age = #{age}
</when>
<otherwise>
AND status = 'ACTIVE'
</otherwise>
</choose>
</where>
</select>
```
这个SQL语句中的choose、when和otherwise元素根据传入的参数map中的name和age是否为null,决定是否添加AND name = #{name}或AND age = #{age}或AND status = 'ACTIVE'到SQL语句中。
3. foreach元素:可以用foreach元素来处理一个集合参数,生成多个SQL语句片段。例如:
```
<select id="findUsers" parameterType="map" resultMap="userResultMap">
SELECT * FROM users
<where>
<foreach collection="ids" item="id" separator="OR">
id = #{id}
</foreach>
</where>
</select>
```
这个SQL语句中的foreach元素用来处理传入的参数map中的ids集合,对于集合中的每个元素id,生成一个id = #{id}的SQL语句片段,并用OR连接起来。