mybatis的xml映射文件里写了对数据库的操作,有些sql可能很繁琐,比如有一个方法是根据姓名查找学生,有个是根据身份证id查学生。。。这样的话就很冗余。可以用if来做一定的简化
也就是如果参数中有学生的某个属性,就拼接该属性到需要查询关联的sql中去
举个栗子
<select id="queryByNameOrSex" resultType="student" parameterType="student">
select * from student where 1=1
<if test="sname!=null and sname!=‘‘">
sname=#{sname}
</if>
<if test="ssex!=null">
and ssex=#{ssex}
</if>
</select>
用where 1=1是为了防止如果sname没有的话,就会where and ssex=true;语法报错。这是比较low的解决方法,当然了mybatis早就预料到了这种low方法,所以还提供了另外一个sql标签
<select id="queryByNameOrSex" resultType="student" parameterType="student">
select * from student
<where>
<if test="sname!=null and sname!=‘‘">
and sname=#{sname}
</if>
<if test="ssex!=null">
and ssex=#{ssex}
</if>
</where>
</select>
也就是where标签,然后在每个if标签里都加上and,mybatis会自动识别那个and是不需要的,哇卡卡卡有点智能哦
原文:https://www.cnblogs.com/liuyongbo/p/11006434.html