Where 用于解决 SQL 语句中 where 关键字以及条件中第一个 and 或者 or 的问题
1 2 3 4 5 6
<selectid="findSomethings"parameterType="hashmap"resultType="hashmap"> select name,age,id from user where 1 = 1 <iftest="name != null and name!='' "> and name = #{name}</if> <iftest="level != null and level!='' "> and level= #{level}</if> </select>
由于存在 1=1 这样不太优雅的情况,MyBatis 提供了<where>标签
1 2 3 4 5 6 7 8 9 10 11
<selectid="selectBySallary"resultType="Employee"> SELECT * FROM emp <where> <iftest="min != null"> AND sal >= #{min} </if> <iftest="max != null"> AND sal <= #{max} </if> </where> </select>
<selectid="selectBySallary"resultType="Employee"> SELECT * FROM emp <choose> <whentest="min != null and max != null"> WHERE sal >= #{min} AND sal <= #{max} </when> <whentest="min != null"> WHERE sal >= #{min} </when> <whentest="max != null"> WHERE sal <= #{max} </when> <otherwise></otherwise> </choose> </select>
<selectid="selectInDeptnos"resultType="Employee"> SELECT * FROM emp WHERE deptno IN <foreachcollection="list"item="deptno"open="("separator=","close=")"> #{deptno} </foreach> </select>
foreach 主要用户循环迭代,各个属性含义如下:
collection:要迭代的集合
item:当前从集合中迭代出的元素
open:开始字符
separator:结束字符
index:迭代的是 List 集合,index 表示当前元素的下标;迭代的是 Map 集合,index 表示当前元素的 key