示例:批量插入商品类别
实体类:
/**
* @author XiaoPengCheng
* @create 2019-06-22 15:50
*
* 商品类别
*/
public class ProductCategory implements Serializable {
private Long productCategoryId;
private Long shopId;
private String productCategoryName;
private Integer priority;
private Date createTime;
public Long getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(Long productCategoryId) {
this.productCategoryId = productCategoryId;
}
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public String getProductCategoryName() {
return productCategoryName;
}
public void setProductCategoryName(String productCategoryName) {
this.productCategoryName = productCategoryName;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "ProductCategory{" +
"productCategoryId=" + productCategoryId +
", shopId=" + shopId +
", productCategoryName='" + productCategoryName + '\'' +
", priority=" + priority +
", createTime=" + createTime +
'}';
}
}
mapper层:
/**
* 批量新增商品类别
* @param productCategoryList
* @return
*/
@InsertProvider(type = ProductCategoryProvider.class, method = "batchInsertProductCategory")
Integer batchInsertProductCategory(List<ProductCategory> productCategoryList);
使用@InsertProvider注解指定了type=ProductCategoryProvider类,所以,在ProductCategoryProvider中,我们需要写:
public String batchInsertProductCategory(Map map){
List<ProductCategory> productCategoryList = (List<ProductCategory>) map.get("list");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("INSERT INTO product_category(product_category_name,priority,shop_id) VALUES ");
MessageFormat messageFormat = new MessageFormat(
"(#'{'list[{0}].productCategoryName},#'{'list[{0}].priority},#'{'list[{0}].shopId})"
);
for (int i = 0; i < productCategoryList.size(); i++) {
stringBuilder.append(messageFormat.format(new Object[] {i}));
if (i < productCategoryList.size() - 1)
stringBuilder.append(",");
}
return stringBuilder.toString();
}
当我们接受到list参数时,就通过map获取参数进行处理。
单元测试:
@Test
public void batchInsertProductCategory(){
ProductCategory productCategory = new ProductCategory();
productCategory.setProductCategoryName("商品类别1");
productCategory.setPriority(1);
productCategory.setShopId(1L);
ProductCategory productCategory1 = new ProductCategory();
productCategory1.setProductCategoryName("商品类别2");
productCategory1.setPriority(3);
productCategory1.setShopId(1L);
List<ProductCategory> productCategoryList = new ArrayList<>();
productCategoryList.add(productCategory);
productCategoryList.add(productCategory1);
Integer effectedNum = productCategoryMapper.batchInsertProductCategory(productCategoryList);
System.out.println("影响行数:" + effectedNum);
}
最后通过控制台显示受影响行数为2,数据库中也产生了相应的记录。