mybatis批量插入

mybatis批量插入

在mybatis中时常进行批量插入,批量插入需要用到mybatis 的foreach标签

foreach 标签元素含义

item:表示集合中每一个元素进行迭代时的别名

index(下标从0开始):指 定一个名字,用于表示在迭代过程中,每次迭代到的位置

collection:指定要遍历的集合

open:表示该语句以什么开始

separator:表示在每次进行迭代之间以什么符号作为分隔 符

close: 表示以什么结束

colletion不同类型

collection属性值为list

批量插入list:

@Test
public void testBatchInsert() throws  Exception{
   //Map<String,Object> map  = new HashMap<String, Object>();
   //map.put("specId","my heart will go on");
   List<Map<String,Object>> list  = new ArrayList<Map<String,Object>>();
   Map<String,Object> map1  = new HashMap<String, Object>();
   map1.put("specId","aaaa");
   map1.put("specValue",10);
   Map<String,Object> map2  = new HashMap<String, Object>();
   map2.put("specId","aaaa");
   map2.put("specValue",20);
   Map<String,Object> map3  = new HashMap<String, Object>();
   map3.put("specId","aaaa");
   map3.put("specValue",30);

   list.add(map1);
   list.add( map2);
   list.add(map3 );

   //map.put("specValue",list);
   // 批量插入 list
   bookDao.batchInsert(list);
   
}

sql:

<insert id="batchInsert" parameterType="Map"  useGeneratedKeys="true" keyProperty="id">
   INSERT INTO book(`name`,`number`) VALUES
   <foreach collection="list" item ="temp" separator=",">
      (
      #{temp.specId},
      #{temp.specValue}
      )
   </foreach>
</insert>

collection的属性值为array

批量插入数组:

@Test
public void  testBatchInsertArrays(){
   Integer[]  arrays = new Integer[]{1,2,3};
   bookDao.batchInsertArray(arrays);
}

sql:

<insert id="batchInsertArray"  >
   INSERT INTO book(`name`,`number`) VALUES
   <foreach collection="array" item ="temp" index="index" separator=",">
      (
      "aaa",
      #{index} 
      )
   </foreach>
</insert>

collection 为Map(包含list)参数的key值

map中key 为 where 条件 , value 为修改值时:需要注意的事jdbcUrl 必须加上allowMultiQueries=true

@Test
public void  testBatchUpdateBook(){
    Map<String,Object>  map = new HashMap<String, Object>();
    map.put("aaa",10);
    map.put("zhang",200);
    bookDao.batchUpdateBook(map);
}

sql:

<update id="batchUpdateBook" parameterType="Map">
   <foreach item="value" index="key" collection="Book.entrySet()" separator=";">
           UPDATE book SET
           number= ${value}
           WHERE name = #{key}
   </foreach>
</update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值