mybatis 批量入库 参数list+pojo

mybatis批量入库,如果参数是List,没什么好说,但有时参数是一个list+pojo,要批量插入list的值,同时还要用到pojo中某些属性,以下为几种写法:

  • 参数是数组 String[] 和 String
//java
Map<String, Object> params = new HashMap<>();
 params.put("userId", userId);
 params.put("creator", creator);
 params.put("roles", ids);  // ids为String[]
 roleMapper.saveRolesByUserId(params);

// mapper
 void saveRolesByUserId(Map<String, Object> params);
// xml
  <insert id="saveRolesByUserId" parameterType="map">
        insert ignore into user_role
        <trim prefix="(" suffix=")" suffixOverrides=",">
            user_id, role_id, add_user, add_time
        </trim>
        <trim prefix="values" suffixOverrides=",">
            <foreach collection="roles" item="roleid" index="index" separator=",">
                (#{userId},#{roleid},#{creator},now())
            </foreach>
        </trim>
    </insert>
  • 参数是List和 String
// scala
    val map1 = new util.HashMap[String,Object]()
    map1.put("brand_type",brand_name)
    map1.put("list",sonList.asJava)
    mapper.saveRecordByBrand(map1)
// mapper
void saveRecordByBrand(Map<String, Object> params);
// xml
 <insert id="saveRecordByBrand" parameterType="map">
    insert into third_dealer (id, dealer_name, phone,
    address, zbx, zby,
    brand_type, dealer_id,city)
    VALUES
    <foreach collection="list" item="item" index="index" separator="," >
      (#{item.id,jdbcType=INTEGER}, #{item.dealer_name,jdbcType=VARCHAR}, #{item.phone,jdbcType=VARCHAR},
      #{item.address,jdbcType=VARCHAR}, #{item.zbx,jdbcType=VARCHAR}, #{item.zby,jdbcType=VARCHAR},
      #{brand_type,jdbcType=VARCHAR}, #{item.dealer_id,jdbcType=INTEGER},#{item.city,jdbcType=VARCHAR})
    </foreach>
  </insert>
  • 参数是List和 pojo / 或 List 和 Map
// java
Map<String, Object> params = new HashMap<>();
params.put("list", list); 
params.put("pojo", b);  // b为pojo对象 或 map对象
m1.saveRecordByBrandPojo(params);
// mapper
void saveRecordByBrandPojo(Map<String, Object> params);
// xml
 <insert id="saveRecordByBrandPojo" parameterType="map">
    insert into third_dealer (id, dealer_name, phone,
    address, zbx, zby,
    brand_type, dealer_id,city)
    VALUES
    <foreach collection="list" item="item" index="index" separator="," >
      (#{item.id,jdbcType=INTEGER}, #{item.dealer_name,jdbcType=VARCHAR}, #{item.phone,jdbcType=VARCHAR},
      #{item.address,jdbcType=VARCHAR}, #{item.zbx,jdbcType=VARCHAR}, #{item.zby,jdbcType=VARCHAR},
      #{pojo.brand_type,jdbcType=VARCHAR}, #{item.dealer_id,jdbcType=INTEGER},#{item.city,jdbcType=VARCHAR})
    </foreach>
  </insert>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值