1.循环list<简单类型>
dao接口的形参是 List<简单类型> 这样的:
List<Student> quaryByIds(@Param("idList") List<Integer> idList);
/**
* 1.collection:要遍历的目标集合
* open:循环开始时的字符;close:循环结束时的字符
* item:遍历出的集合成员,自己定义的变量
* separator:结合成员之间的分隔符
* #{item}:注意与item="item"中的的值相同
*/
select * from student
where 1 = 1
<if test="idList != null and idList.size()>0">//注意这个集合判空
and id in
<foreach collection="idList" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
/**
*sql效果如下:
*select
*FROM student
*WHERE 1=1 and id in ( 1 , 2 , 9 );
*/
2.循环list<对象类型>
dao接口的形参是 List<对象类型> 这样的:
List<Student> quaryByxObj(@Param("studentList") List<Student> studentList);
mapper文件
<select id="quaryByxObj" resultType="com.example.springbootmy.entity.Student">
select * from student
where 1=1
<if test="studentList != null and studentList,size()>0">
and id in
<foreach collection="studentList" open="(" close=")" separator="," item="stu">
#{stu.id}
</foreach>
</if>
</select>
额外说明:如果java实现foreach标签的功能,代码如下
思路是拼成一个sql的字符串传递给mybatis.
/**
* Java拼装sql语句
*/
@PostMapping("mybatis/quaryByIds1")
public List<Student> quaryByIds1(@RequestBody List<Integer> idList){
StringBuffer sql = new StringBuffer();
sql.append("select * from student where id in");
sql.append("(");
for (Integer id : idList) {
sql.append(id);//添加id到sql字符串
sql.append(",");//添加成员之间分隔符
}
sql.deleteCharAt(sql.length()-1);//删除最后一个逗号
sql.append(")");
return crudService.quaryByIds1(sql);
}
dao接口
List<Student> quaryByIds1(@Param("sql") StringBuffer sql);
mapper文件
<select id="quaryByIds1" resultType="com.example.springbootmy.entity.Student">
${sql}
</select>