MyBatis realizes batch addition

When performing back-end operations, batch addition is always indispensable, not much to say, paste the code below

Mybatis code:

	<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>

Using dynamic SQL, the foreach tag is used to traverse. The
collection is defined as a list and added in the form of a list.
Item: Customizable, preferably related to the entity class.
Index: Counter
Separator: Separator, such as (?, ?, ?,? ), (?, ?, ?,?)

Junit test code

	@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);
	}

Result display
SQL statement

Data result

Guess you like

Origin blog.csdn.net/hyx1249273846/article/details/113817392