一、if标签
条件判断标签
<select id="test" resultMap="BaseResultMap" parameterType="map">
select *from user where 1=1
<if test="username != null and username!= ''">
and username like %${username}%
</if>
</select>
在if标签中的test语句相当于一个判断,如果满足test的条件,执行if里面的语句
where后面1=1,是为了解决当if条件都不为true时,sql语句不合法导致报错的问题
二、where标签
<select id="testWhere" resultMap="BaseResultMap" parameterType="map">
select *from user
<where>
<if test="username != null and username!= ''">
and username like %${username}%
</if>
</where>
</select>
执行时,where标签会自动转化为一个where
如果if条件为false,where标签会去掉这个and,让语句正确执行
where标签可以过滤掉条件语句中第一个and或or
三、trim标签
trim标签用于控制(添加/删除)sql语句的前缀及后缀,其属性:
属性 | 描述 |
---|---|
prefix | 指定sql语句拼接的前缀 |
subfix | 指定sql语句拼接的后缀 |
prefixOverrides | 指定sql语句前面要去除的关键字或字符,如AND 逗号 括号等 |
suffixOverrides | 指定sql语句后面要去除的关键字或字符 |
<select id="testWhere" resultMap="BaseResultMap" parameterType="map">
select *from user
<trim prefix="WHERE" prefixOverrides="AND | OR">
<if test="username != null and username!= ''">
and username like %${username}%
</if>
</trim>
</select>
这里trim标签给sql语句添加了前缀where,并会根据条件去掉多余的and或or
四、 choose、otherwize标签
相当于if…if…else…if…else…
<select id="chooseTest" parameterType="map" resultType="map">
select * from user
<where>
<choose>
<when test="username!= null">
and username= #{username}
</when>
<when test="age != null">
and age = #{age}
</when>
<otherwise>
and sex = #{sex}
</otherwise>
</choose>
</where>
</select>
mybatis会依次顺序判断各choose中的条件,当when某个条件满足时,就会跳出choose,即只选择第一个满足条件的when,如果choose中的条件都不满足,则执行otherwise中的语句
五、set标签
- set标签的作用和where类似
- set元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号
六、foreach标签
其属性:
collection属性值有三种情况:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了
- 在list集合中
(批量删除)
<delete id="deleteBath" parameterType="java.util.List">
DELETE FROM user WHERE id IN
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item.id}
</foreach>
</delete>
(批量添加)
<insert id="insertBath" parameterType="java.util.List">
INSERT INTO user(id, name, age,update_time)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id},#{item.name},#{item.age},now())
</foreach>
</insert>
- 在map集合中
(批量删除)
<delete id="deleteBath" parameterType="java.util.Map">
DELETE FROM user WHERE id IN
<foreach collection="ids" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
七、sql
使用sql标签把常用的sql语句作为一个sql片段,然后在其他地方使用include标签可以使用sql片段
<sql id="select">
select * from user
</sql>
<select id="findStudent" resultType="Student">
<include refid="select"></include>
<where>
<if test="username!= null">
username= #{username}
</if>
<if test="password != null">
and password = #{password }
</if>
</where>
</select>