<!-- 使用动态sql 测试if标签 --> <selectid="getEmployeeByConditon"resultMap="emp"> select * from employee where id = #{id} <iftest="name != null and name!=''"> and name like #{name} </if> <iftest="salary != null and salary != 0"> and name = #{salary} </if> </select>
where标签
可能遇到的情况
有时通过if条件判断之后导致后续一个条件都没有,此时SQL就变成了
1
select * from employee where
此时将不需要使用where条件
也有可能会出现有一个条件符合,但是会多出来一个and,此时SQL就变成了
1
select * from employee whereandid = 1
很明显,这个多出来的and会导致报错
出现这种情况有两种方式解决
可以使用1=1条件
可以使用where标签,where会将where标签中拼接的sql中开头多出来的and或者or去掉
可以使用trim
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<!-- 使用动态sql 测试if和where标签 --> <selectid="getEmployeeByCondition"resultMap="emp"> select * from employee <where> <iftest="id != null and id != 0"> and id = #{id} </if> <iftest="name != null and name!=''"> and name like #{name} </if> <iftest="salary != null and salary != 0"> and salary = #{salary} </if> </where> </select>
<selectid="getEmployeeByCondition"resultMap="emp"> select * from employee <trimprefix="where"suffixOverrides="and | or"> <iftest="id != null and id != 0"> id = #{id} and </if> <iftest="name != null and name!=''"> name like #{name} and </if> <iftest="salary != null and salary != 0"> salary = #{salary} and </if> </trim> </select>
<selectid="getEmployeeByConditionChoose"resultMap="emp"> select * from employee <trimprefix="where"suffixOverrides="and | or"prefixOverrides="and | or"> <!-- 有id时用id查,有name时用name查,否则查询所有 --> <choose> <whentest="id != null and id != 0"> id = #{id} and </when> <whentest="name != null and name!=''"> name like #{name} and </when> <otherwise>
<selectid="selectUserByCondition"resultType="User"> select * from user <iftest="_parameter != null"> <where> <iftest="id != null and id != 0"> and id = #{_parameter.id} </if> <iftest="name != null"> and name = #{_parameter.name} </if> <iftest="account != null and account != 0"> and account = #{_parameter.account} </if> </where> </if> </select>
bind绑定
bind可以将OGNL表达式的值绑定到一个变量中,并将其绑定到当前上下文,方便后来引用这个变量的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<selectid="selectUserByCondition"resultType="User"> select * from user <where> <iftest="id != null and id != 0"> and id = #{id} </if> <iftest="name != null"> <bindname="_name"value="'%'+name+'%'"/> and name like #{_name} </if> <iftest="account != null and account != 0"> and account = #{account} </if> </where> </select>