动态sql之 foreach 标签

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>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值