mybatis批量插入
************************************************************************************
当有大量数据需要插入时,可以配置mybatis批量插入,实现高效插入的两种方式
************************************************************************************
方式一:使用foreach标签
<insert id="insertBatch" parameterType="java.util.List"> <trim prefix="insert into md_net_index (" suffix=") " suffixOverrides=","> NET_INDEX_ID, ACCOUNT_ID, CORP_ID, NET_BATCH_ID, ROAD_NETWORK_ID, REMARK, CREATE_TIME, UPDATE_TIME, CREATE_USER, UPDATE_USER, </trim> <trim prefix="values " suffixOverrides=","> <foreach collection="list" index="index" item="item" separator=","> <trim suffix=")" prefix="(" suffixOverrides=","> <if test="item.netIndexId != null"> #{item.netIndexId,jdbcType=VARCHAR}, </if> <if test="item.accountId != null"> #{item.accountId,jdbcType=VARCHAR}, </if> <if test="item.corpId != null"> #{item.corpId,jdbcType=VARCHAR}, </if> <if test="item.netBatchId != null"> #{item.netBatchId,jdbcType=VARCHAR}, </if> <if test="item.roadNetworkId != null"> #{item.roadNetworkId,jdbcType=VARCHAR}, </if> <if test="item.remark != null"> #{item.remark,jdbcType=VARCHAR}, </if> <if test="item.createTime != null"> #{item.createTime,jdbcType=VARCHAR}, </if> <if test="item.updateTime != null"> #{item.updateTime,jdbcType=VARCHAR}, </if> <if test="item.createUser != null"> #{item.createUser,jdbcType=VARCHAR}, </if> <if test="item.updateUser != null"> #{item.updateUser,jdbcType=VARCHAR}, </if> </trim> </foreach> </trim> </insert>
方法二:通过设置SQLSessionTemplate
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public void insertBatch(String sqlId, int batchCount) {
List<MdNetIndex> pojos = new ArrayList<>();
int result = 1;
if (pojos == null || pojos.size() == 0 || batchCount < 1) {
return;
}
SqlSession batchSqlSession = null;
batchSqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false); // ExecutorType.BATCH批量,ExecutorType.SIMPLE单条(默认),false:取消自动提交
try {
int batchLastIndex = batchCount; // 每批最后一个的下标
int listSize = pojos.size();
for (int index = 0; index < listSize; ) {
if (batchLastIndex >= listSize) {
batchLastIndex = listSize;
batchSqlSession.insert(sqlId, pojos.subList(index, batchLastIndex));
batchSqlSession.commit();
batchSqlSession.clearCache();
break; // 数据插入完毕,退出循环
} else {
batchSqlSession.insert(sqlId, pojos.subList(index, batchLastIndex));
batchSqlSession.commit();
batchSqlSession.clearCache();
index = batchLastIndex; // 设置下一批下标
batchLastIndex = index + (batchCount - 1);
}
}
} catch (Exception e) {
batchSqlSession.rollback();
} finally {
batchSqlSession.close();
}
}
有志之士,共同学习