在进行后端的操作时,批量添加总是少不了,话不多说,下面贴上代码
Mybatis代码:
代码语言:javascript复制 <insert id="batchInsert" parameterType="java.util.List">
INSERT INTO
tb_product_category(product_category_name, priority,
create_time, shop_id)
VALUES
<foreach collection="list" item="productCategory" index="index"
separator=",">
(
#{productCategory.productCategoryName},
#{productCategory.priority},
#{productCategory.createTime},
#{productCategory.shopId}
)
</foreach>
</insert>
使用动态SQL,foreach标签进行遍历 collection定义为 list ,以列表的形式添加进去 item:可自定义,最好与实体类相关 index:计数器 separator:分隔符,比如这种( ?, ?, ?, ? ) , ( ?, ?, ?, ? )
Junit测试类代码
代码语言:javascript复制 @Test
public void testABatchInsertProductCategory(){
ProductCategory productCategory = new ProductCategory();
productCategory.setProductCategoryName("商品类别1");
productCategory.setPriority(1);
productCategory.setCreateTime(new Date());
productCategory.setShopId(1L);
ProductCategory productCategory2 = new ProductCategory();
productCategory2.setProductCategoryName("商品类别2");
productCategory2.setPriority(2);
productCategory2.setCreateTime(new Date());
productCategory2.setShopId(1L);
List<ProductCategory> productCategoryList = new ArrayList<ProductCategory>();
productCategoryList.add(productCategory);
productCategoryList.add(productCategory2);
int effectedNum = productCategoryDao.batchInsertProductCategory(productCategoryList);
assertEquals(2, effectedNum);
}
结果展示