如果不加上恒成立条件,则SQL语句为select * from t_emp where and age = ? and sex = ? and email = ?,此时where会与and连用,SQL语句会报错
如果加上一个恒成立条件,则SQL语句为select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?,此时不报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<!--List<Emp> getEmpByCondition(Emp emp);--> <selectid="getEmpByCondition"resultType="Emp"> select * from t_emp where 1=1 <iftest="empName != null and empName !=''"> and emp_name = #{empName} </if> <iftest="age != null and age !=''"> and age = #{age} </if> <iftest="sex != null and sex !=''"> and sex = #{sex} </if> <iftest="email != null and email !=''"> and email = #{email} </if> </select>
<!--List<Emp> getEmpByCondition(Emp emp);--> <selectid="getEmpByCondition"resultType="Emp"> select * from t_emp <where> <iftest="empName != null and empName !=''"> emp_name = #{empName} </if> <iftest="age != null and age !=''"> and age = #{age} </if> <iftest="sex != null and sex !=''"> and sex = #{sex} </if> <iftest="email != null and email !=''"> and email = #{email} </if> </where> </select>
注意:where标签不能去掉条件后多余的and/or
1 2 3 4 5 6 7 8 9
```xml <!--这种用法是错误的,只能去掉条件前面的and/or,条件后面的不行--> <iftest="empName != null and empName !=''"> emp_name = #{empName} and </if> <iftest="age != null and age !=''"> age = #{age} </if> ```
1.3、trim
trim用于去掉或添加标签中的内容
常用属性
prefix:在trim标签中的内容的前面添加某些内容
suffix:在trim标签中的内容的后面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容
若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!--List<Emp> getEmpByCondition(Emp emp);--> <selectid="getEmpByCondition"resultType="Emp"> select * from t_emp <trimprefix="where"suffixOverrides="and|or"> <iftest="empName != null and empName !=''"> emp_name = #{empName} and </if> <iftest="age != null and age !=''"> age = #{age} and </if> <iftest="sex != null and sex !=''"> sex = #{sex} or </if> <iftest="email != null and email !=''"> email = #{email} </if> </trim> </select>
<!--int deleteMoreByArray(Integer[] eids);--> <deleteid="deleteMoreByArray"> delete from t_emp where eid in <foreachcollection="eids"item="eid"separator=","open="("close=")"> #{eid} </foreach> </delete>