mybatisplus批量插入数据
对于mybatis-plus的批量操作,一句话:少量数据可以使用,大量数据建议手写sql。
不建议mybatis-plus使用批量操作,也是循环一条一条操作。废话不多说上demo。
1.导入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency>
2.Dao层
package cn.mindgd.mapper;
import cn.mindgd.domain.WarehouseDetail;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface WarehouseDetailMapper extends BaseMapper<WarehouseDetail> {
/**
* @author: JiaXinMa
* @description: 批量插入
* @date: 2021/8/27
*/
@Insert("<script>" +
"INSERT INTO warehouse_detail(warehouse_record_id,material_id,a_number,b_number)VALUES" +
"<foreach collection='warehouseDetails' item='warehouseDetail' separator=','> " +
"(#{warehouseDetail.warehouseRecordId},#{warehouseDetail.materialId},#{warehouseDetail.aNumber},#{warehouseDetail.bNumber})" +
"</foreach> " +
"</script>")//批量建议手写sql
boolean insertBatch(@Param("warehouseDetails") List<WarehouseDetail> warehouseDetails);
}
3.业务层
package cn.mindgd.service; import cn.mindgd.domain.WarehouseDetail; import com.baomidou.mybatisplus.extension.service.IService; public interface WarehouseDetailService extends IService<WarehouseDetail> { }
4.业务实现层
package cn.mindgd.service.impl; import cn.mindgd.domain.WarehouseDetail; import cn.mindgd.mapper.WarehouseDetailMapper; import cn.mindgd.service.WarehouseDetailService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class WarehouseDetailServiceImpl extends ServiceImpl<WarehouseDetailMapper, WarehouseDetail> implements WarehouseDetailService { }
5.测试
@Test
public void testSaveBatch() {
List<WarehouseDetail> ws = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
WarehouseDetail warehouseDetail = new WarehouseDetail();
warehouseDetail.setWarehouseRecordId(i);
warehouseDetail.setANumber(i + 10.2);
warehouseDetail.setBNumber(i + 11.2);
ws.add(warehouseDetail);
}
long start = System.currentTimeMillis();
warehouseDetailMapper.insertBatch(ws);//自己写的sql
// warehouseDetailService.saveBatch(ws);//mybatis-plus的方法
long end = System.currentTimeMillis();
System.out.println("耗时:"+ (end-start)+"毫秒");
}
6.效果:
调用mybatis-plus,批量插入少量数据可以用。
调用自己写的,大量数据建议手写sql
想看更多精彩内容,可以关注我的CSDN