【1】if标签
通过if标签我们可以动态的传入参数,以帮助我们适应不同的情景下的sql查询。
案例:
select * from user
<where>
<if test="id != 0"> id = #{id}</if>
<if test="username != null"> and username = #{username}</if>
<if test="password != null"> and password = #{password}</if>
</where>
这样,届时传入一个对象,就可以根据id进行查询,可以根据用户名进行查询,或者根据用户名和密码进行查询。
【2】where标签
通过where标签,在sql语句中,对where关键字进行补足,并且当进行and等关键字操作,并且不用担心and是否是多余的情况。
案例:
select * from user
<where>
<if test="id != 0"> id = #{id}</if>
<if test="username != null"> and username = #{username}</if>
<if test="password != null"> and password = #{password}</if>
</where>
通过where关键字,我们就不需要对如果id == 0的时候,我们就不用担心 select * from user where and username = ***的情况了,Mybatis会自动将and去除的。
注意:and关键字只能放在开头
username = #{username} and 错误
【3】set标签
当我们使用update更新语句的时候,可以使用set标签。补足set关键字,并且避免“,”的影响。
案例:
update user
<set>
<if test="name != null">
name = #{name},
</if>
<if test="age != -1">
age = #{age},
</if>
</set>
<where>
id = #{id}
</where>
这样,即使age != -1条件成立,age = #{age},也不会影响语句,因为Mybatis会将,去除掉。
【4】trim
trim标签可以结合insert语句,进行操作插入操作,可以去除“(”,“)”,“,”等。我感觉比较鸡肋.....
prefix:表示前缀字符
suffix:表示后缀字符
suffixOverrides:表示分隔字符
案例:
insert into
user
<trim prefix="(" suffix=")" suffixOverrides=",">
id,
<if test="name != null">
name,
</if>
<if test="age != -1">
age,
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
null,
<if test="name != null">
#{name},
</if>
<if test="age != -1">
#{age},
</if>
</trim>
【5】foreach
foreach标签,循环标签,可以对传入的数据进行遍历操作,适合in等关键字。
collection:集合内容
open:前缀字符
close:后缀字符
item:元素
separator:分隔符
案例:
delete from
user
<where>
id in
<foreach collection="list" open="(" close=")" item="item" separator=",">
#{item}
</foreach>
</where>
【6】sql与include
当映射文件中,重复语句太多的时候,可以通过sql进行抽取,然后通过include关键字进行引入。
案例:
<sql id="select_user">
select name , age
</sql>
<select id="select02" resultType="user">
<include refid="select_user"/> from user
</select>