Fork me on GitHub

batch-insert-mybatis

前言

后台开发中,批量往数据库写数据是一个很常见的功能,下面就简单实现一下使用 mybatis 来 batch 写入。

实现介绍

添加依赖

在项目的 pom.xml 中配置 mybatis 及 mysql 相关的依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
Mapper 接口

在这个 mapper 的 接口类中添加批量新增的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.jack.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {

/***
* <p>
* 批量插入用户数据
* </p>
* @author jack
*
* @param userList 用户数据列表
*/
void batchInsertSelective(@Param("userList") List<User> userList);
}
Mapper xml

在这个 mapper 的 xml 中实现批量新增的方法。

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<insert id="batchInsertSelective" parameterType="java.util.List">
<foreach collection="userList" item="user" index="index" separator=";">
insert into tb_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="user.id != null">
id,
</if>
<if test="user.userName != null">
user_name,
</if>
<if test="user.userPassword != null">
user_password,
</if>
<if test="user.userSalt != null">
user_salt,
</if>
<if test="user.phone != null">
phone,
</if>
<if test="user.createUser != null">
create_user,
</if>
<if test="user.createTime != null">
create_time,
</if>
<if test="user.updateUser != null">
update_user,
</if>
<if test="user.updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="user.id != null">
#{user.id,jdbcType=VARCHAR},
</if>
<if test="user.userName != null">
#{user.userName,jdbcType=CHAR},
</if>
<if test="user.userPassword != null">
#{user.userPassword,jdbcType=VARCHAR},
</if>
<if test="user.userSalt != null">
#{user.userSalt,jdbcType=VARCHAR},
</if>
<if test="user.phone != null">
#{user.phone,jdbcType=VARCHAR},
</if>
<if test="user.createUser != null">
#{user.createUser,jdbcType=VARCHAR},
</if>
<if test="user.createTime!= null">
#{user.createTime,jdbcType=VARCHAR},
</if>
<if test="user.updateUser!= null">
#{user.updateUser,jdbcType=VARCHAR},
</if>
<if test="user.updateTime!= null">
#{user.updateTime,jdbcType=TIMESTAMP},
</if>
</trim>
</foreach>
</insert>
使用

使用 spring 注入,然后调用即可

1
2
3
4
5
6
7
8
9
@Autowired
private UserMapper userMapper;

public void testMybatisBatchInsertUser(int count) {
long t1 = System.currentTimeMillis();
userMapper.batchInsertSelective(getUserList(count));
System.out.println("【mybatis-batch】插入条数:【" + count + "】耗时:【"
+ (System.currentTimeMillis() - t1) + "】");
}

结语

到此,使用 mybatis 来 batch 写入数据的实现就介绍完了,后续继续其他方式的批量写入 …

-------------本文结束感谢您的阅读-------------
如果您对博主的原创满意,欢迎您继续支持下博主~