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是不需要的,哇卡卡卡有点智能哦
----------------------------------------foreach标签----------------------------------------------------------
循环标签,适用与集合类型的参数取值,比如说某个对象类型的属性是list,就可以用这种方式了,举个栗子
StudentClass中有一个List<Integer> ids;这样的属性,当输入参数是班级对象时,要查这个班级的说有学生,就可以这样了如下
<select id="queryByClassIds" resultType="student" parameterType="studentClass">
select * from student where sid in
(
<if test="sids!=null and sids.size>0">
<foreach collection="sids" item="sid" separator=",">
#{sid}
</foreach>
</if>
)
</select>
foreach和java中的for each非常像,指定collection就是一个集合的名字,然后item是自己用的值的名字,再指定数据之间的分隔符即可。
注意事项,如果传入参数不是某个对象中的集合类别,而就是简单的List<Integer>或者是int[] 这样的类型,则再mapper.xml中有约定的collection名字
<select id="queryByArray" resultType="student" parameterType="int[]">
select * from student where sid in
(
<if test="array!=null and array.length>0">
<foreach collection="array" item="sid" separator=",">
#{sid}
</foreach>
</if>
)
</select>
如果是List,list 如果是简单类型数组,array,是对象数组,parameterType=“Object[]” 必须这样写。。。传入参数的名字,并不是程序中传入的那个参数。。。是一种约定