Skip to content

Commit ebbd4c1

Browse files
committed
spring-boot-mybatisplus-v3
1 parent 8ae2cd0 commit ebbd4c1

File tree

10 files changed

+323
-58
lines changed

10 files changed

+323
-58
lines changed

spring-boot-mybatisplus-v3/pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@
5151
<artifactId>spring-boot-starter-test</artifactId>
5252
<scope>test</scope>
5353
</dependency>
54+
<dependency>
55+
<groupId>org.springframework</groupId>
56+
<artifactId>spring-jdbc</artifactId>
57+
</dependency>
5458
</dependencies>
5559

5660
<build>

spring-boot-mybatisplus-v3/src/main/java/com/example/mapper/UserMapper.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22

33
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
44
import com.example.model.User;
5+
import java.util.ArrayList;
56
import java.util.List;
67
import org.apache.ibatis.annotations.Mapper;
8+
import org.apache.ibatis.annotations.Param;
9+
import org.apache.ibatis.annotations.Select;
710

811
@Mapper
912
public interface UserMapper extends BaseMapper<User> {
@@ -12,5 +15,16 @@ public interface UserMapper extends BaseMapper<User> {
1215

1316
boolean saveBatchCustom(List<User> list);
1417

18+
@Select("SELECT count(*) as sum FROM user")
19+
Integer UserSum();
1520

21+
@Select("select * from user LIMIT #{startLen},5000")
22+
ArrayList<User> subList(@Param("startLen") int startLen);
23+
24+
25+
@Select("SELECT count(*) as sum FROM user where id like concat('%',0,'%')")
26+
Integer UserSumV2();
27+
28+
@Select("select * from user where id like concat('%',0,'%') LIMIT #{startLen},5000")
29+
ArrayList<User> subListV2(@Param("startLen") int startLen);
1630
}
Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package com.example.service;
22

3+
import com.baomidou.mybatisplus.extension.service.IService;
34
import com.example.model.User;
45
import java.util.List;
56

6-
public interface UserService {
7+
public interface UserService extends IService<User> {
78

8-
boolean saveBatchByNative(List<User> list);
9+
void saveBatchByNative(List<User> list);
910

1011
boolean saveBatchCustom(List<User> list);
1112

13+
void jdbcBatchInsert(List<User> list, final int batchSize);
1214
}

spring-boot-mybatisplus-v3/src/main/java/com/example/service/impl/UserServiceImpl.java

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,54 @@
55
import com.example.mapper.UserMapper;
66
import com.example.model.User;
77
import com.example.service.UserService;
8+
import java.sql.Date;
9+
import java.sql.PreparedStatement;
10+
import java.sql.SQLException;
811
import java.util.List;
9-
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
13+
import org.springframework.jdbc.core.JdbcTemplate;
1014
import org.springframework.stereotype.Service;
15+
import org.springframework.transaction.annotation.Transactional;
1116

1217
@Service
1318
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
14-
implements UserService {
19+
implements UserService {
1520

16-
@Autowired
17-
private UserMapper userMapper;
21+
private final UserMapper userMapper;
1822

19-
public boolean saveBatchByNative(List<User> list) {
20-
return userMapper.saveBatchByNative(list);
21-
}
22-
public boolean saveBatchCustom(List<User> list){
23-
return userMapper.saveBatchCustom(list);
24-
}
23+
private final JdbcTemplate jdbcTemplate;
24+
25+
public UserServiceImpl(UserMapper userMapper, JdbcTemplate jdbcTemplate) {
26+
this.userMapper = userMapper;
27+
this.jdbcTemplate = jdbcTemplate;
28+
}
29+
30+
public void saveBatchByNative(List<User> list) {
31+
userMapper.saveBatchByNative(list);
32+
}
33+
34+
public boolean saveBatchCustom(List<User> list) {
35+
return userMapper.saveBatchCustom(list);
36+
}
37+
38+
@Transactional
39+
public void jdbcBatchInsert(List<User> list, final int batchSize) {
40+
String sql = "insert into user (name,password,createtime) values(?,?,?)";
41+
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
42+
@Override
43+
public void setValues(PreparedStatement ps, int i) throws SQLException {
44+
User userPO = list.get(i);
45+
ps.setString(1, userPO.getName());
46+
ps.setString(2, userPO.getPassword());
47+
ps.setDate(3, new Date(new java.util.Date().getTime()));
48+
}
49+
50+
@Override
51+
public int getBatchSize() {
52+
return list.size();
53+
}
54+
});
55+
}
2556

2657

2758
}

spring-boot-mybatisplus-v3/src/main/java/com/example/web/UserController.java

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.example.model.User;
44
import com.example.service.impl.UserServiceImpl;
5+
import java.time.LocalDateTime;
56
import java.util.ArrayList;
67
import java.util.List;
78
import org.springframework.beans.factory.annotation.Autowired;
@@ -12,22 +13,26 @@
1213
@RequestMapping("/u")
1314
public class UserController {
1415

15-
@Autowired
16-
private UserServiceImpl userService;
16+
private final UserServiceImpl userService;
1717

18-
/**
19-
* 批量插入(自定义)
20-
*/
21-
@RequestMapping("/mysavebatch")
22-
public boolean mySaveBatch(){
23-
List<User> list = new ArrayList<>();
24-
// 待添加(用户)数据
25-
for (int i = 0; i < 1000; i++) {
26-
User user = new User();
27-
user.setName("test:"+i);
28-
user.setPassword("123456");
29-
list.add(user);
30-
}
31-
return userService.saveBatchCustom(list);
18+
public UserController(UserServiceImpl userService) {
19+
this.userService = userService;
20+
}
21+
22+
/**
23+
* 批量插入(自定义)
24+
*/
25+
@RequestMapping("/save-batch")
26+
public boolean mySaveBatch() {
27+
List<User> list = new ArrayList<>();
28+
// 待添加(用户)数据
29+
for (int i = 0; i < 1000; i++) {
30+
User user = new User();
31+
user.setName("test:" + i);
32+
user.setPassword("123456");
33+
user.setCreateTime(LocalDateTime.now());
34+
list.add(user);
3235
}
36+
return userService.saveBatchCustom(list);
37+
}
3338
}

spring-boot-mybatisplus-v3/src/main/resources/mapper/UserMapper.xml

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,17 @@
22
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
33
<mapper namespace="com.example.mapper.UserMapper">
44
<insert id="saveBatchByNative">
5-
INSERT INTO `USER`(`NAME`,`PASSWORD`) VALUES
6-
<foreach collection="list" separator="," item="item">
7-
(#{item.name},#{item.password})
8-
</foreach>
5+
INSERT INTO `USER`(`NAME`,`PASSWORD`) VALUES
6+
<foreach collection="list" separator="," item="item">
7+
(#{item.name},#{item.password})
8+
</foreach>
9+
</insert>
10+
<insert id="saveBatchCustom">
11+
INSERT INTO `USER`(`NAME`,`PASSWORD`,`CREATETIME`)
12+
values
13+
<foreach collection="list" item="item" separator=",">
14+
(#{item.name},#{item.password},#{item.createTime})
15+
</foreach>
916
</insert>
1017

1118
</mapper>
Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,58 @@
11
-- ----------------------------
2+
-- 删除用户
3+
-- ----------------------------
4+
drop
5+
user test@'127.0.0.1';
6+
-- ----------------------------
7+
-- 创建用户
8+
-- ----------------------------
9+
create
10+
user test@'127.0.0.1'
11+
identified by 'test'
12+
with max_connections_per_hour 500000 max_updates_per_hour 600000 max_user_connections 700000 max_queries_per_hour 400000;
13+
14+
-- ----------------------------
15+
-- 赋予权限
16+
-- ----------------------------
17+
grant create, insert, select, update on testdb.* to test@'127.0.0.1';
18+
-- ----------------------------
219
-- 创建数据库
320
-- ----------------------------
421
SET NAMES utf8mb4;
5-
SET FOREIGN_KEY_CHECKS = 0;
6-
DROP DATABASE IF EXISTS `testdb`;
7-
CREATE DATABASE `testdb`;
22+
SET
23+
FOREIGN_KEY_CHECKS = 0;
24+
DROP
25+
DATABASE IF EXISTS `testdb`;
26+
CREATE
27+
DATABASE `testdb`;
828
USE `testdb`;
929

1030
-- ----------------------------
1131
-- 创建 user 表
1232
-- ----------------------------
1333
DROP TABLE IF EXISTS `user`;
14-
CREATE TABLE `user` (
15-
`id` int(11) NOT NULL AUTO_INCREMENT,
16-
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
17-
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
18-
`createtime` datetime NULL DEFAULT CURRENT_TIMESTAMP,
19-
PRIMARY KEY (`id`) USING BTREE
34+
CREATE TABLE `user`
35+
(
36+
`id` int(11) NOT NULL AUTO_INCREMENT,
37+
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
38+
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
39+
`createtime` datetime NULL DEFAULT CURRENT_TIMESTAMP,
40+
PRIMARY KEY (`id`) USING BTREE
2041
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
2142

2243
-- ----------------------------
2344
-- 添加测试数据
2445
-- ----------------------------
25-
INSERT INTO `user` VALUES (1, '赵云', '123456', '2021-09-10 18:11:16');
26-
INSERT INTO `user` VALUES (2, '张飞', '123456', '2021-09-10 18:11:28');
27-
INSERT INTO `user` VALUES (3, '关羽', '123456', '2021-09-10 18:11:34');
28-
INSERT INTO `user` VALUES (4, '刘备', '123456', '2021-09-10 18:11:41');
29-
INSERT INTO `user` VALUES (5, '曹操', '123456', '2021-09-10 18:12:02');
46+
INSERT INTO `user`
47+
VALUES (1, '赵云', '123456', '2021-09-10 18:11:16');
48+
INSERT INTO `user`
49+
VALUES (2, '张飞', '123456', '2021-09-10 18:11:28');
50+
INSERT INTO `user`
51+
VALUES (3, '关羽', '123456', '2021-09-10 18:11:34');
52+
INSERT INTO `user`
53+
VALUES (4, '刘备', '123456', '2021-09-10 18:11:41');
54+
INSERT INTO `user`
55+
VALUES (5, '曹操', '123456', '2021-09-10 18:12:02');
3056

31-
SET FOREIGN_KEY_CHECKS = 1;
57+
SET
58+
FOREIGN_KEY_CHECKS = 1;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.example;
2+
3+
4+
import com.baomidou.mybatisplus.core.conditions.Wrapper;
5+
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
6+
import com.example.mapper.UserMapper;
7+
import com.example.model.User;
8+
import com.example.service.UserService;
9+
import java.time.LocalDateTime;
10+
import java.util.ArrayList;
11+
import java.util.List;
12+
import lombok.extern.slf4j.Slf4j;
13+
import org.junit.jupiter.api.BeforeEach;
14+
import org.junit.jupiter.api.Test;
15+
import org.springframework.beans.factory.annotation.Autowired;
16+
import org.springframework.boot.test.context.SpringBootTest;
17+
import org.springframework.util.StopWatch;
18+
19+
@Slf4j
20+
@SpringBootTest
21+
public class BatchInsertDataTest {
22+
23+
private static final int MAX_COUNT = 10000;
24+
25+
@Autowired
26+
private UserMapper userMapper;
27+
@Autowired
28+
private UserService userService;
29+
30+
@BeforeEach
31+
public void atest1() {
32+
Wrapper<User> query = new QueryWrapper<User>();
33+
userMapper.delete(query);
34+
log.info("清空数据表");
35+
}
36+
37+
/**
38+
* 543
39+
*/
40+
@Test
41+
public void mybatisForeach() {
42+
StopWatch sw = new StopWatch("testBatchInsert2");
43+
sw.start();
44+
List<User> list = getUsers();
45+
userService.saveBatchCustom(list);
46+
sw.stop();
47+
log.info("saveBatchCustom:{}", sw.getTotalTimeMillis());
48+
}
49+
50+
/**
51+
* 1960
52+
*/
53+
@Test
54+
public void mybatisPlusBatchSave() {
55+
StopWatch sw = new StopWatch("mybatisPlusBatchSave");
56+
sw.start();
57+
List<User> list = getUsers();
58+
userService.saveBatch(list, 500);
59+
sw.stop();
60+
log.info("mybatisPlusBatchSave:{}", sw.getTotalTimeMillis());
61+
}
62+
63+
/**
64+
* 1555
65+
*/
66+
@Test
67+
public void jdbcBatchSave() {
68+
StopWatch sw = new StopWatch("jdbcBatchSave");
69+
sw.start();
70+
List<User> list = getUsers();
71+
userService.jdbcBatchInsert(list, 500);
72+
sw.stop();
73+
log.info("jdbcBatchSave:{}", sw.getTotalTimeMillis());
74+
}
75+
76+
private static List<User> getUsers() {
77+
List<User> list = new ArrayList<>();
78+
User user;
79+
for (int i = 0; i < MAX_COUNT; i++) {
80+
user = new User();
81+
user.setName("test" + i);
82+
user.setPassword("p" + i);
83+
user.setCreateTime(LocalDateTime.now());
84+
list.add(user);
85+
}
86+
return list;
87+
}
88+
89+
}

0 commit comments

Comments
 (0)