1. 程式人生 > >Mybatis 批量插入、批量更新

Mybatis 批量插入、批量更新

        合理的使用批量插入、更新對效能優化有很大的作用,速度明顯快了N倍。        要注意資料庫連線串後面要新增:&allowMultiQueries=true,表示一個sql可以通過分號分割為多個獨立sql。        批量插入的最大限制主要是看你整條sql的長度大小,所以可以根據自身sql長度的大小來配置這個要分批的每批的個數。批量插入Dao
123public Integer saveStudents(List<Student> students) {return super.getSqlSession().insert("StudentMapper.insertStudents"
, students);}
Mapper
1234567891011<insert id="insertStudents" parameterType="java.util.List">insert into t_student(city_id)values<foreach collection="list" item="itm" index="index" separator=",">(#{itm.city_id})</foreach></insert>
批量更新Dao
123public Integer updateStudents(List<Student> students) {
return super.getSqlSession().update("StudentMapper.updateStudents", students);}
Mapper
12345678910111213<update id="updateStudents" parameterType="java.util.List"><foreach collection="list" item="item" index="index" open=""close="" separator=";">UPDATE t_studnet<set><if test="item.name != null"
>name= #{item.name}</if></set>WHERE id = #{item.id}AND age = #{item.age}</foreach></update>
List分批的工具類
123456789101112131415161718192021222324/*** 分批list* @param sourceList*            要分批的list* @param batchCount*            每批list的個數* @return List<List<Object>>*/public static List<List<?>> batchList(List<?> sourceList, int batchCount) {List<List<?>> returnList = new ArrayList<>();int startIndex = 0// 從第0個下標開始while (startIndex < sourceList.size()) {int endIndex = 0;if (sourceList.size() - batchCount < startIndex) {endIndex = sourceList.size();else {endIndex = startIndex + batchCount;}returnList.add(sourceList.subList(startIndex, endIndex));startIndex = startIndex + batchCount; // 下一批}return returnList;}