mybatis批量插入

mybatis批量插入xml


oracle使用

java代码:

public int batchInsertAlarmSmsSend(List<AlarmSmsSendEntity> smsSendList);


xml代码:

	<insert id="batchInsertAlarmSmsSend">
		insert into bus_sms (id,send_to,content,event_id,event_title,create_date)
		<foreach collection="list" item="item" index="index" separator=" UNION ALL " >
		SELECT   
		#{item.id},#{item.sendTo},#{item.content},#{item.eventId},#{item.eventTitle},#{item.createDate}
		FROM DUAL
		</foreach>
	</insert>


mysql使用

xml代码:

	insert into t_train_record (add_time,emp_id,activity_id,flag) 
	values
	<foreach collection="list" item="item" index="index" separator="," >
		(#{item.addTime},#{item.empId},#{item.activityId},#{item.flag})
	</foreach>




mysql使用
### MyBatis 批量插入实现方式 #### 使用 `<foreach>` 标签进行批量插入MyBatis 中,`<foreach>` 标签用于遍历集合并构建 SQL 语句。这种方式适用于大多数场景下的批量插入操作。 ```xml <insert id="batchInsert"> INSERT INTO users (username, password) VALUES <foreach collection="list" item="item" index="index" open="" separator="," close=""> (#{item.username}, #{item.password}) </foreach> </insert> ``` 此方法允许将多个值组合成单个 SQL 插入语句[^1]。 #### 设置 `ExecutorType.BATCH` 进行批量处理 另一种高效的方法是设置执行器类型为 `Batch`,这可以在一定程度上减少与数据库之间的交互次数,从而提升性能: ```java SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); for (User user : userList) { mapper.insert(user); } sqlSession.commit(); } finally { sqlSession.close(); } ``` 当使用 `ExecutorType.BATCH` 时,所有的更新命令会被缓存起来直到调用了 commit 或者 flushStatements() 方法才会真正发送到数据库服务器[^3]。 #### 自定义批量插入逻辑 对于更复杂的业务需求,还可以考虑编写自定义的批量插入逻辑来优化特定情况下的性能表现。例如分批次提交数据以避免内存溢出等问题。 ```java public void customBatchInsert(List<User> users){ int batchSize = 1000; SqlSession sqlSession = null; try{ sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); UserMapper mapper = sqlSession.getMapper(UserMapper.class); for(int i=0;i<users.size();i++){ mapper.insert(users.get(i)); if((i+1)%batchSize==0 || (i+1)==users.size()){ sqlSession.flushStatements(); sqlSession.clearCache(); } } sqlSession.commit(); }catch(Exception e){ if(sqlSession!=null){ sqlSession.rollback(); } throw new RuntimeException(e.getMessage(),e); }finally{ if(sqlSession != null){ sqlSession.close(); } } } ``` 这种方法能够更好地控制每次向数据库传输的数据量大小,适合处理非常大规模的数据集[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值