mybatis批量更新

1.先看DAO层


?
1
2
3
4
5
6
publicvoidupdateList(List<AddService> oldAddServiceList) {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,true);
        session.update("AddServiceMapper.batchUpdate",oldAddServiceList);
        session.commit();
        session.close();
    }


当然DAO层最上方类中注入上sqlSessionFactory

?
1
2
@Resource(name ="sqlSessionFactory")
    privateSqlSessionFactory sqlSessionFactory;

?
1
sqlSessionFactory.openSession(ExecutorType.BATCH,true);

mybatis批量更新_第1张图片

详细了解请点击  http://www.cnblogs.com/xcch/articles/2042298.html

2.再看XML配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<updateid="batchUpdate"parameterType="java.util.List">
        <foreachcollection="list"item="item"index="index"separator=";">
            update sp_add_service set
                SERVICE_NAME = #{item.serviceName},
                SERVICE_TYPE = #{item.serviceType},
                PRICE = #{item.price},
                DESCRIPTION = #{item.description},
                PRICE_RATE = #{item.priceRate},
                IS_REQUIRED = #{item.isRequired},
                MODIFY_TIME = now()
            where ID = #{item.id}
        </foreach>
    </update>


3.再看Service层

?
1
2
3
4
@Transactional
    publicvoidupdateOldAddServces(List<AddService> oldAddServiceList) {
        addServiceDao.updateList(oldAddServiceList);
    }
加上事务注解,防止出异常。好让事务回滚 


注意!!!以上代码全照例子写后发现批量更新还是不行,后来百度了一下,数据库连接代码后面加上&allowMultiQueries=true

jdbc:mysql://111.111.111.111:3306/ibada?characterEncoding=UTF-8&allowMultiQueries=true


然后再执行,发现OK了。批量更新大工告成。



批量插入和批量删除大体一样,就给上XML供大家参考,不做详细描述。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- 批量插入 -->
    <insertid="batchInsert"parameterType="java.util.List">
        insert into sp_add_service( <includerefid="AddService_Column_List"/> )
        values
        <foreachcollection="list"item="item"index="index"separator=",">
            (#{item.id}, #{item.logisticsLtdId}, #{item.serviceName}, #{item.serviceType},
            #{item.price},#{item.description},#{item.priceRate},
            #{item.parentId}, #{item.isRequired}, now(), now())
        </foreach>
    </insert>
 
 
    <deleteid="batchDelete">
        delete from sp_add_service
        where LOGISTICS_LTD_ID = #{logisticsLtdId}
        and  ID  not in
        <foreachitem="item"index="index"collection="oldServiceIds"
                 open="("separator=","close=")">
                 #{item}
        </foreach>
    </delete>



关于上面的博客里面的内容一直没仔细看,可能原博主那个true写的不对,应该是fasle,

?
1
(ExecutorType.BATCH,false);
在最近又用到mybatis的批量插入时干脆自己做了一个小测试。

测试环境,mysql数据库。

测试内容,5000条数据的插入。

测试Dao层代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Repository
publicclassTruckSourceDaoextendsBaseDao{
    @Resource(name ="sqlSessionFactory")
    privateSqlSessionFactory sqlSessionFactory;
 
    publicInteger batchInsertList(List<TruckSource> truckSources){
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        for(inti =0;i < truckSources.size(); i++) {
            session.insert("TruckSource.insertOne",truckSources.get(i));
        }
        session.commit();
        session.clearCache();
        returnnull;
    }
 
    publicInteger insertList(List<TruckSource> truckSources){
        returngetSqlSession().insert("TruckSource.insertBatch",truckSources);
    }
 
    publicInteger batchInsertLists(List<TruckSource> truckSources){
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        session.insert("TruckSource.insertBatch",truckSources);
        session.commit();
        session.clearCache();
        returnnull;
    }
 
}


Mapper.xml里面代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<sqlid="TruckSource_Column_List">
        TRUCK_OWNER_ID,TRUCK_SOURCE_TYPE,INITIATION_PROVINCE_CODE,INITIATION_CITY_CODE,INITIATION_DISTRICT_CODE,DESTINATION_PROVINCE_CODE,DESTINATION_CITY_CODE,DESTINATION_DISTRICT_CODE,
        SURPLUS_LOAD,SURPLUS_LENGTH,SURPLUS_VOLUME,START_TIME,VALID_DATE,STATE,NOTICE,CREATE_TIME,MODIFY_TIME
    </sql>
    <insertid="insertBatch"parameterType="java.util.List">
         insert into sp_truck_source(<includerefid="TruckSource_Column_List"/>)
         values
         <foreachcollection="list"item="item"index="index"separator=",">
            (#{item.truckOwnerId}, #{item.truckSourceType}, #{item.initiationProvinceCode}, #{item.initiationCityCode},
            #{item.initiationDistrictCode}, #{item.destinationProvinceCode}, #{item.destinationCityCode}, #{item.destinationDistrictCode},
            #{item.surplusLoad}, #{item.surplusLength}, #{item.surplusVolume}, #{item.startTime},
            #{item.validDate},#{item.state},#{item.notice},
            now(), now())
         </foreach>
    </insert>
 
    <insertid="insertOne"parameterType="TruckSource">
        insert into sp_truck_source(<includerefid="TruckSource_Column_List"/>)
        values (#{truckOwnerId},#{truckSourceType},#{initiationProvinceCode},#{initiationCityCode},#{initiationDistrictCode},#{destinationProvinceCode},#{destinationCityCode},#{destinationDistrictCode},
        #{surplusLoad},#{surplusLength},#{surplusVolume},#{startTime},#{validDate},#{state},#{notice},now(),now())
    </insert>



单元测试代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ="classpath:applicationContext.xml")
publicclassTTTT {
 
    @Resource
    privateTruckSourceDao truckSourceDao;
 
    @Test
    publicvoidinsert() {
        List<TruckSource> truckSources =newArrayList<TruckSource>();
        for(inti =0;i <5000; i++) {
            TruckSource truckSource =newTruckSource();
            truckSource.setDestinationDistrictCode(i+"");
            truckSource.setDestinationCityCode(i+"");
            truckSource.setDestinationProvinceCode(i+"");
            truckSource.setInitiationCityCode(i+"");
            truckSource.setInitiationDistrictCode(i+"");
            truckSource.setInitiationProvinceCode(i+"");
            truckSources.add(truckSource);
        }
        Long beginTime = System.currentTimeMillis();
        truckSourceDao.batchInsertList(truckSources);
        System.out.println("batchInsert:"+(System.currentTimeMillis() - beginTime));
 
        beginTime = System.currentTimeMillis();
        truckSourceDao.insertList(truckSources);
        System.out.println("foreach insert:"+(System.currentTimeMillis() - beginTime));
 
        beginTime = System.currentTimeMillis();
        truckSourceDao.batchInsertLists(truckSources);
        System.out.println("batch foreach insert:"+(System.currentTimeMillis() - beginTime));
    }
 
}


测试方法种类,3种:

1.batchInsertList 插入时单独开一个session用

?
1
SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);

然后下面for循环依次单个插入

2.在mapper.xml里面写foreach sql插入


3.加上ExecutoerType.Batch,再在mapper.xml里面写foreach sql插入


最后实验结果是第三种执行时间最短:

{insert3=5128, insert1=146085, insert2=5625}

上面是数据量为5000情况下的实验结果。

在数据量为1000的情况下,第2种是2000多毫秒,第三种是800多毫秒,所以差距还是比较大的。


你可能感兴趣的:(mybatis批量更新)