mybatis中foreach的用法

来源:互联网 发布:南平政务数据开放 编辑:程序博客网 时间:2024/06/08 17:52

1.场景还原

    工作中,有很多地方需要用到批量删除或批量插入,或者是批量更新,抑或是批量查询,这样的需求难免会用到mybatis中的foreach标签

2.foreach介绍

<foreach>标签的用法:
6个参数:
collection:要循环的集合

index:循环索引;

item:集合中的一个元素(item和collection,按foreach循环理解);

open:以什么开始;

close:以什么结束;

separator:循环内容之间以什么分隔

mybatis接受的参数分为:(1)基本类型;(2)对象;(3)List;(4)数组;(5)Map

接下来笔者主要对list,数组,map做详细讲解:

3.实现方案

①入参为list,collection为list

底层mapper:

<!--批量删除--><update id="deleteWorkshopByIds" parameterType="Integer" >   update workshop set status =0   where id in   <foreach collection="list" index="i" item="id" open="(" separator="," close=")">      #{id}   </foreach></update>

dao层申明:

Integer deleteWorkshopByIds(List<Integer> ids);

mapper测试

@Testpublic void test4(){    List<Integer> ids = new ArrayList<>();    ids.add(1);    ids.add(2);    ids.add(3);    Integer i = workshopDao.deleteWorkshopByIds(ids);    logger.info("删除:"+i);}
测试结果:


②入参为数组,collection为array

底层mapper:

<update id="deleteWorkshopByArray" parameterType="Integer" >   update workshop set status =0   where id in   <foreach collection="array" index="i" item="id" open="(" separator="," close=")">      #{id}   </foreach></update>
dao层申明:

Integer deleteWorkshopByArray(int[] arrays);
mapper测试:

@Testpublic void test5(){   int[] array = new int[]{3,4,5};    Integer i = workshopDao.deleteWorkshopByArray(array);    logger.info("删除:"+i);}
测试效果:


③入参为map,collection为集合的名称

底层mapper:

<select id="getWorkShopByMap" resultType="com.cckj.bean.Workshop" parameterType="java.util.Map">   SELECT * FROM workshop where status = #{status} AND company_id IN   <foreach collection="ids" item="id" index="i" open="(" separator="," close=")">      #{id}   </foreach></select>
dao层申明:

List<Workshop> getWorkShopByMap(HashMap map);
mapper测试:

@Testpublic void test6(){    List<Integer> ids = new ArrayList<>();    ids.add(1);    ids.add(2);    ids.add(3);    HashMap map = new HashMap();    map.put("ids",ids);    map.put("status",1);    List<Workshop> list= workshopDao.getWorkShopByMap(map);    logger.info("查询的个数"+list.size());}
或者

@Testpublic void test6(){    int[] ids = new int[]{1,2,3};    HashMap map = new HashMap();    map.put("ids",ids);    map.put("status",1);    List<Workshop> list= workshopDao.getWorkShopByMap(map);    logger.info("查询的个数"+list.size());}
测试效果:


在这里值得注意的是,实现类中put到map中集合的是key要与collection的值相等;

好了,今天就这样吧!我是张星,欢迎加入博主技术交流群,群号:313145288



原创粉丝点击