MyBatis 批量插入的 3 种方式!还有谁不会? | 您所在的位置:网站首页 › mybatis批量insert的几种方式 › MyBatis 批量插入的 3 种方式!还有谁不会? |
数据库使用的是sqlserver,JDK版本1.8,运行在SpringBoot环境下,对比3种可用的方式: 反复执行单条插入语句xml拼接sql批处理执行先说结论:少量插入请使用反复插入单条数据,方便。数量较多请使用批处理方式。(可以考虑以有需求的插入数据量20条左右为界吧,在我的测试和数据库环境下耗时都是百毫秒级的,方便最重要)。 无论何时都不用xml拼接sql的方式。 代码拼接SQL的xml newId()是sqlserver生成UUID的函数,与本文内容无关 代码语言:javascript复制 INSERT INTO tb_item VALUES (newId(),#{item.uniqueCode},#{item.projectId},#{item.name},#{item.type},#{item.packageUnique}, #{item.isPackage},#{item.factoryId},#{item.projectName},#{item.spec},#{item.length},#{item.weight}, #{item.material},#{item.setupPosition},#{item.areaPosition},#{item.bottomHeight},#{item.topHeight}, #{item.serialNumber},#{item.createTime}Mapper接口 Mapper是 mybatis插件tk.Mapper 的接口,与本文内容关系不大 代码语言:javascript复制public interface ItemMapper extends Mapper { int insertByBatch(List itemList); }Service类 代码语言:javascript复制@Service public class ItemService { @Autowired private ItemMapper itemMapper; @Autowired private SqlSessionFactory sqlSessionFactory; //批处理 @Transactional public void add(List itemList) { SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false); ItemMapper mapper = session.getMapper(ItemMapper.class); for (int i = ; i |
CopyRight 2018-2019 实验室设备网 版权所有 |