引言
由於我們對於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就是當前值 #{變量名}就能取出變量的值也就是當前遍歷出的元素