1.if:根据标签test属性所对应的表达式觉得标签中的内容是否拼接到sql中
当第一句sql出错时,会出现异常可以通过添加一个恒成立条件解决
<select id="getEmpByConditionOne" resultType="Emp">
<!-- 添加恒成立条件确保sql语句不会出错 -->
select * from t_emp where 1=1
<if test="empName!=null and empName!=''">
emp_name=#{empName}
</if>
<if test="age!=null and age!=''">
and age=#{age}
</if>
<if test="sex!=null and sex!=''">
and sex=#{sex}
</if>
<if test="email!=null and email!=''">
and email=#{email}
</if>
</select>
2.where:
* 当where标签中有内容,会自动生成where关键字,并且将内容前多余的and或or去掉
* 当where标签中没有内容,where标签没有任何效果
* 注:where标签不能将and或or放在内容之后。
<select id="getEmpByConditionTwo" resultType="Emp">
select * from t_emp
<where>
<if test="empName!=null and empName!=''">
emp_name=#{empName}
</if>
<if test="age!=null and age!=''">
and age=#{age}
</if>
<if test="sex!=null and sex!=''">
and sex=#{sex}
</if>
<if test="email!=null and email!=''">
and email=#{email}
</if>
</where>
</select>
3.trim:
* 有内容:
* prefix|suffix:将trim标签中内容前面或后面添加指定内容
* suffixOverrides|prefixOverrides:将trim标签中内容前面或后面去掉指定内容
* 无内容: trim标签无效果
<select id="getEmpByCondition" resultType="Emp">
select <include refid="empColumns"></include> from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName!=null and empName!=''">
emp_name=#{empName} and
</if>
<if test="age!=null and age!=''">
age=#{age} or
</if>
<if test="sex!=null and sex!=''">
sex=#{sex}and
</if>
<if test="email!=null and email!=''">
email=#{email}
</if>
</trim>
</select>
4.choose,when,otherwise 相当于if...else if...else
* when至少一个,otherwise(else)最多一个
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName !=null and empName!=''">
emp_name=#{empName}
</when>
<when test="age !=null and age!=''">
age=#{age}
</when>
<when test="sex !=null and sex!=''">
sex=#{sex}
</when>
<when test="email !=null and email!=''">
email=#{email}
</when>
<otherwise>
did=1
</otherwise>
</choose>
</where>
</select>
5.foreach实现批量操作
<foreach collection="eids"(当前需要循环的数组或集合 ) item="eid" ( 数组或集合中的每一个元素 ) separator="," (分隔符(每一次循环体中的分隔 )) open="(" close=")" (标签所循环所有的内容)
5.1 用in查询
<delete id="deleteMoreByArrayOne">
delete from t_emp where eid in
<!--遍历 需要对整体加括号或者在open和close中加
在in中不需要添加等于条件-->
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
5.2用where判断条件
<delete id="deleteMoreByArray">
delete from t_emp where
<foreach collection="eids" item="eid" separator="or">
eid=#{eid}
</foreach>
</delete>
6.插入操作
<insert id="insertMoreByArray">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.em ail},null)
</foreach>
</insert>