简述mybatis中的三种动态标签,以及他们含有的属性和作用
时间: 2024-03-17 19:41:39 浏览: 25
Mybatis中的三种动态标签分别是`<if>`、`<choose>`和`<foreach>`。
1. `<if>`标签:用于在SQL语句中进行条件判断,如果条件成立,则拼接该条件下的SQL语句。该标签有一个`test`属性,用于指定条件的判断表达式。
示例代码:
```
<select id="getUserList" resultMap="userMap">
select * from user
<where>
<if test="username != null">
and username like concat('%', #{username}, '%')
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>
```
2. `<choose>`标签:用于在多个条件中进行选择,类似于Java中的switch语句。该标签下可以包含多个`<when>`标签和一个`<otherwise>`标签。如果`<when>`标签中的条件满足,则拼接该条件下的SQL语句,如果所有条件都不满足,则拼接`<otherwise>`标签下的SQL语句。
示例代码:
```
<select id="getUserList" resultMap="userMap">
select * from user
<where>
<choose>
<when test="username != null">
and username like concat('%', #{username}, '%')
</when>
<when test="age != null">
and age = #{age}
</when>
<otherwise>
and status = 1
</otherwise>
</choose>
</where>
</select>
```
3. `<foreach>`标签:用于在SQL语句中进行循环操作,可以对一个集合进行遍历,然后将集合中的元素拼接到SQL语句中。该标签有三个属性,分别是`collection`(指定要遍历的集合)、`item`(指定集合中每个元素的别名)、`separator`(指定元素之间的分隔符)。
示例代码:
```
<select id="getUserListByIds" resultMap="userMap">
select * from user
<where>
<foreach collection="ids" item="id" separator="or">
id = #{id}
</foreach>
</where>
</select>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)