Mybatis批量插入3种方法

原文链接:https://blog.csdn.net/qq_43486404/article/details/126637141

使用Mybatis框架批量插入的3种方法:多次调用insert方法、foreach标签、batch模式

一、 多次调用insert方法
每插入一条数据都调用一次insert方法,这种方法适用于数据量小时使用,频繁使用会浪费数据库资源。
1
二、 foreach标签
一次存入多条数据,使用方法如下:
1
<insert id="insert1" keyColumn="goods_id" keyProperty="goodsId" parameterType="com.shop.test.pojo.entity.test"
useGeneratedKeys="true">
insert into test (shop_id, test_type_id,)
values
<foreach collection="record" item="item" separator="," >
(#{item.shopId,jdbcType=BIGINT}, #{item.goodsTypeId,jdbcType=BIGINT})
</foreach>
</insert>`
1
2
3
4
5
6
7
8
三、 batch模式
一次存入多条数据,使用方法如下:
xml代码:
1
2
<insert id="insert" keyColumn="goods_id" keyProperty="goodsId" parameterType="com.shop.test.pojo.entity.test"
useGeneratedKeys="true">
insert into test (shop_id, test_type_id)
values
(#{shopId,jdbcType=BIGINT}, #{goodsTypeId,jdbcType=BIGINT})
</insert>
1
2
3
4
5
6
后端java代码:

//先引入
@Resource
private SqlSessionFactory sqlSessionFactory;
//具体实现
SqlSession sqlSession=sqlSessionFactory.openSession(ExecutorType.BATCH);
List<test> insertlist=new ArrayList<>();
test test1=new test((long)1,(long)12);
for(int i=0;i<100000;i++){
insertlist.add(test1);
}
try{
Long mm=System.currentTimeMillis();
TestDao mapper=sqlSession.getMapper(TestDao.class);
insertlist.stream().forEach(e->{
mapper.insert(e);
});
sqlSession.clearCache();
sqlSession.commit();
}catch(Exception e){
System.out.println(e);
}finally{
sqlSession.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
四、三种方法比较
1)insert
适用于少量数据插入,每次使用都要调用数据库连接,频繁使用会浪费资源,效率低
2)foreach标签
使用foreach可以减少数据库连接的调用,效率比inser高
3)batch模式
当数据特别多时效率比foreach标签高

posted @ 2022-12-21 12:54  枫树湾河桥  阅读(1005)  评论(0编辑  收藏  举报
Live2D