Fork me on GitHub

batch-insert-mybatis-provider

前言

后台开发中,批量往数据库写数据是一个很常见的功能,下面就简单实现一下使用 mybatis-provider 来 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>
provider 逻辑实现类

新建一个 provider 类,用于实现 batch 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
import com.fy.entity.User;

import java.util.List;

/**
* Description:batch insert 的 provider 实现
*
* @author fy
* @version 1.0
*/
public class UserProvider {

public String batchInsert(List<User> list) {
StringBuilder sb = new StringBuilder("INSERT INTO tb_user (id,user_name,user_password," +
"user_salt,phone,create_user,update_user) VALUES");
for (int i = 0; i < list.size(); i++) {
User user = list.get(i);
if (i > 0) {
sb.append(",");
}
sb.append("(");
sb.append("'").append(user.getId()).append("',");
sb.append("'").append(user.getUserName()).append("',");
sb.append("'").append(user.getUserPassword()).append("',");
sb.append("'").append(user.getUserSalt()).append("',");
sb.append("'").append(user.getPhone()).append("',");
sb.append("'").append(user.getCreateUser()).append("',");
sb.append("'").append(user.getUpdateUser()).append("'");
sb.append(")");
}
sb.append(";");
return sb.toString();
}
}
mapper 接口类

在该表的 mapper 接口类中,绑定上刚刚的 provider。

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
import com.fy.entity.User;
import com.fy.service.provider.UserProvider;
import org.apache.ibatis.annotations.InsertProvider;

import java.util.List;

/**
* <p>
* Mapper 接口
* </p>
*
* @author fy
*/
public interface UserMapper {

/***
* <p>
* 批量插入数据,通过 InsertProvider 方式
* </p>
* @author fy
*
* @param list 数据
*/
@InsertProvider(type = UserProvider.class, method = "batchInsert")
void batchInsertByProvider(List<User> list);
}
使用

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

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

public void testProviderBatchInsertUser(int count) {
long t1 = System.currentTimeMillis();
userMapper.batchInsertByProvider(getUserList(count));
System.out.println("【UserMapper-provider】插入条数:【" + count + "】耗时:【"
+ (System.currentTimeMillis() - t1) + "】");
}

结语

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

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