Java inserts data into the database in batches, prompting the server to receive the maximum number of parameters

problem scenario

When inserting data into the database in batches, it prompts the server to receive too many parameters, and the server can receive up to 2100 parameters.
At this point, divide 2100 by the number of fields in the entity to get the number of commits each time.

  1. When it is not greater than this threshold, it can be directly inserted in batches through mapper.xml;
  2. When it is greater than this threshold, data can be inserted in batches in batches.

java code

int resultInt = 0;
int batchCount = 90; // 每批commit的个数
int batchLastIndex = batchCount;// 每批最后一个的下标
for (int index = 0; index < list.size(); ) {
    
    
	if (batchLastIndex >= list.size()) {
    
    
		batchLastIndex = list.size();
		resultInt = resultInt * userDao.insertByList(list.subList(index, batchLastIndex));
		break;// 数据插入完毕,退出循环
	} else {
    
    
		resultInt = resultInt * userDao.insertByList(list.subList(index, batchLastIndex));
		index = batchLastIndex;// 设置下一批下标
		batchLastIndex = index + (batchCount - 1);
	}
}

mapper.xml code

<insert id="insertByList">
	insert into user
		(Id, Code, TimePoint, MaxValue, MonValue)
	values
	<foreach collection="list" item="item" index="index" separator=",">
		(#{item.id}, #{item.Code}, #{item.timePoint}, #{item.maxValue}, #{item.monValue})
	</foreach>
</insert>

Reference from the original text: About MyBatis batch insert SqlServer report: Too many parameters are provided in the RPC request. Should be at most 2100.

Guess you like

Origin blog.csdn.net/qq_44726330/article/details/129148554