本文已参与「新人创作礼」活动,一起开启掘金创作之路。
IF
test 代表判断 后面添加要用and where 1=1 为了后面直接会and不会报错
<select id="getTeacher" resultType="Teacher">
select * from teacher where 1=1
<if test="tid!=null and tid !=''" >
tid=#{tid}
</if>
<if test="tname !=null and tname !=''">
and tname=#{tname}
</if>
</select>
where标签 如果有内容时会自动生成where关键字并且将内容前多余的and和or去掉 where标签 如果没有内容时,此时where会没有任何效果 where标签 不能将内容后的and去掉 所以只能在内容前面加and
WHERE
<select id="getTeacher" resultType="Teacher">
select * from teacher
<where>
<if test="tid!=null and tid !=''" >
tid=#{tid}
</if>
<if test="tname !=null and tname !=''">
and tname=#{tname}
</if>
</where>
</select>
TRIM
prefix|suffix:将trim标签中内容前面或者后面添加内容 suffixOverrides|prefixOverrides:将trim标签中内容前面或者后面去掉指定内容 若标签中没有任何内容时,标签也没有任何效果
<select id="getTeacher" resultType="Teacher">
select * from teacher
<trim prefix="where" suffixOverrides="and|or" >
<if test="tid!=null and tid !=''" >
tid=#{tid}
</if>
<if test="tname !=null and tname !=''">
tname=#{tname} and
</if>
</trim>
</select>
choose where otherwise
if if else else
等于
choose where otherwise
<select id="getTeacher" resultType="Teacher">
select * from teacher
<where>
<choose>
<when test="tid!=null ">
tid=#{tid}
</when>
<when test="tname!=null">
tname=#{tname}
</when>
<otherwise>
tid = 2
</otherwise>
</choose>
</where>
</select>
FOREACH 循环
批量删除
接口
//@Param规定访问访问
int deleteMoreByArrey(@Param("tids") Integer[] tids);
mapper
<delete id="deleteMoreByArrey">
-- int deleteMoreByArrey(Integer[] tids);
delete from teacher where tid in
-- item代表数组中的每一个元素
-- separator 分隔符
-- open 以什么符号开始 close以什么符号结束 就会帮你自动加上符号了(1,2)
<foreach collection="tids" item="tid" separator="," open="(" close=")">
#{tid}
</foreach>
</delete>
第二种批量删除
delete from teacher where
<foreach collection="tids" item="tid" separator="or">
tid=#{tid}
</foreach>
批量添加
接口
int insertMoreList(@Param("techers") List<Teacher> techers);
mapper
<insert id="insertMoreList">
insert into teacher values
<foreach collection="techers" item="i" separator=",">
(null,#{i.tname})
</foreach>
</insert>
SQL 标签
效果就是给你插入的地方放置sql标签值
<!-- 如果有用到以下字段的地方可以直接用sql标签来引用-->
<!-- <include refid="empCloue"> 表示引用sql标签-->
<sql id="empCloue">tid,names,eid,teacher</sql>
<select id="getTeacher" resultType="Teacher">
select <include refid="empCloue"></include> from teacher
<where>
<choose>
<when test="tid!=null ">
tid=#{tid}
</when>
<when test="tname!=null">
tname=#{tname}
</when>
<otherwise>
tid = 2
</otherwise>
</choose>
</where>
</select>