mybatis批量插入有多个list如何使用foreach

本文介绍了一种在数据库操作中实现批量插入多条记录的方法。通过将多个列表转换为一个Map列表,并利用XML文件中的foreach循环进行遍历,从而一次性完成所有数据的插入操作。

如果在使用批量插入的时候有多个list该怎么用一条sql搞定呢。可以给list拼接成一个map然后去循环List<Map>,如下操作

public void tenantAddApp(String tenantId,String appIds,String wxAppIds){
        List<String> app = Arrays.asList(appIds.split(","));
        List<String> wxApp = Arrays.asList(wxAppIds.split(","));
        List<Map> mapList = new ArrayList<>();
        for(int i =0 ;i<app.size(); i++){
            Map map = new HashMap();
            map.put("appId",app.get(i));
            map.put("wxAppId",wxApp.get(i));
            mapList.add(map);
        }
        tenantMapper.tenantAddApp(tenantId,mapList);
    }

 

然后xml中直接去循环读取map指定的值

    void tenantAddApp(@Param("tenantId") String tenantId, @Param("mapList")List<Map> mapList);
    <insert id="tenantAddApp">
        insert into oauth_tenant_applicaion values
        <foreach collection="mapList" item="map" index="index"  separator="," close=";">
            (#{tenantId}, #{map.appId},#{map.wxAppId})
        </foreach>
    </insert>

这样就实现了批量插入多条数据

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值