作用:拼接Sql语句,person有name属性 且 不为null 注意所有 SQL字段大小写忽略,但是 实体类属性区分大小写 第二个拼接语句 开头 需要加 and
<!-- 动态SQL --> <!-- person有name属性 且 不为null --> <!-- 注意所有SQL字段大小写忽略,但是实体类属性区分大小写 --> <!-- 第二个拼接语句 开头 需要加 and --> <select id="queryPersonByNameOrSexWithSqlTag" resultType="mybatis.Person" parameterType="mybatis.Person"> select id,name from person where 1=1 <if test="name != null and name != '' "> and name = #{name} </if> <if test="sex != null and sex != '' "> and sex = #{sex} </if> </select>查询学号为1,2,3的学生信息 输入一个集合 ids = {1,2,3} 迭代的类型:数组、对象数组、集合、属性(Grade类:List ids)
mapper.xml 👇
<!-- <foreach>输入集合 --> <select id="queryPersonWithIdsInGrade" parameterType="mybatis.Grade" resultType="person"> select * from person <where> <if test="ids!=null and ids.size>0"> <foreach collection="ids" open="and id in (" close=")" item="id" separator=","> #{id} </foreach> </if> </where> </select>测试 👇
List<Integer> ids = new ArrayList<>(); ids.add(1); ids.add(2); ids.add(3); Grade grade = new Grade(ids); System.out.println(queryPersonWithIdsInGrade(grade));无论在编写时,用的什么参数名,在mapper.xml中 必须 要用 array 代替数组名
mapper.xml 👇
<!-- <foreach>输入数组 int[] --> <select id="queryPersonWithIdsInArr" parameterType="int[]" resultType="person"> select * from person <where> <if test="array!=null and array.length>0"> <foreach collection="array" open="and id in (" close=")" item="id" separator=","> #{id} </foreach> </if> </where> </select>无论在编写时,用的什么参数名,在mapper.xml中 必须 要用 list 代替集合 名
mapper.xml 👇
<!-- <foreach>输入集合 list 必须用list代替数组名 --> <select id="queryPersonWithIdsInList" parameterType="list" resultType="person"> select * from person <where> <if test="list!=null and list.size>0"> <foreach collection="list" open="and id in (" close=")" item="id" separator=","> #{id} </foreach> </if> </where> </select>对象数组的输入要用Object [ ]
mapper.xml 👇
<!-- <foreach>输入对象数组 Person [] person = {p1,p2,p3} --> <select id="queryPersonWithIdsInObjArray" parameterType="Object[]" resultType="person"> select * from person <where> <if test="array!=null and array.length>0"> <foreach collection="array" open="and id in (" close=")" item="person" separator=","> #{person.id} </foreach> </if> </where> </select>