引言
由于我们对于mapper采用的是注解写的sql的方式,而不是常用的xml文件。之后遇到了一个批量插入的问题,找了很久也没有找到合适的方式,至于mybatis官网的使用手册对于这方面的说明也少之又少,后来自己灵机一动,没想到真的成功了。于是贴出来供大家参考,不合适之处请不吝赐教
批量查询
1 @Select({ 2 "<script>" 3 + "SELECT " 4 + "orders.orderId, product_sku.productId, product_sku.skuName, " 5 + "orders.number, orders.orderPrice,product_sku.skuPrice, " 6 + "orders.orderCreate, customer.mobile, shop_keeper.mobile1 as shopKeeperMobile, " 7 + "shop.name, orders.shopId, shop.address, shop.cityCode " 8 + "FROM orders, product_sku, customer, shop, shop_keeper " 9 + "WHERE orders.skuId=product_sku.skuId " 10 + "AND orders.customerId = customer.customerId " 11 + "<if test='orderStatus != null'>" 12 + "AND orders.orderStatus IN " 13 + "<foreach item='status' index='index' collection='orderStatus' open='(' separator=',' close=')'>" 14 + "#{status} " 15 + "</foreach>" 16 + "</if>" 17 + "AND orders.shopId = shop.shopId " 18 + "AND orders.shopId = shop_keeper.shopId " 19 + "ORDER BY customer.mobile DESC, orders.shopId DESC ,orders.orderCreate DESC" 20 + "</script>" 21 }) 22 List<Map<String, Object>> selectOrders(@Param(value="orderStatus")List<Short> orderStatus);
批量更新
1 @Update({ 2 "<script>" 3 + "UPDATE orders SET orderStatus = #{orderStatus} WHERE orderId in " 4 + "<foreach item='item' index='index' collection='orderId' open='(' separator=',' close=')'>" 5 + "#{item}" 6 + "</foreach>" 7 +"</script>" 8 }) 9 int updateOrderStatus(@Param("orderStatus") Short orderStatus,@Param("orderId") String[] orderList);
批量删除
1 @Delete({ 2 3 "<script>delete from substation where id in " 4 + "<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>" 5 + "#{item}" 6 + "</foreach>" 7 + "</script>" 8 }) 9 int deleteList(List<Integer> list);
核心点
不要被上面的一大坨select惊吓到,核心就是
collection: 指定要遍历的集合(三种情况 list,array,map) !!!!在这种使用注解sql的情况下,这里请填写mapper方法中集合的名称 item:将当前遍历出的元素赋值给指定的变量 (相当于for循环中的i) separator:每个元素之间的分隔符 open:遍历出所有结果拼接一个开始的字符 close:遍历出所有结果拼接一个结束的字符 index:索引。遍历list的时候是index就是索引,item就是当前值 #{变量名}就能取出变量的值也就是当前遍历出的元素