mybatis批量插入
阿新 • • 發佈:2018-01-21
list util lists ring bsp pojo reat false exce
************************************************************************************
當有大量數據需要插入時,可以配置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();
}
}
mybatis批量插入