MyBatis的五種批量查詢實(shí)例總結(jié)
一.直接循環(huán)插入
@RestController
@RequestMapping("/mybatis3/user")
@RequiredArgsConstructor
public class UserController {
private final IUserService iUserService;
@GetMapping("/one")
public Long one(){
return iUserService.add();
}
}
Long add();
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
private final UserMapper userMapper;
@Override
public Long add() {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
User user = new User();
user.setUsername("name"+i);
user.setPassword("password"+i);
userMapper.insertUsers(user);
}
long end = System.currentTimeMillis();
System.out.println("耗時(shí):"+( end - start ) + "ms");
return (end-start);
}
}
Integer insertUsers(User user);
<insert id="insertUsers" >
insert into user(username,password)
values (#{username}, #{password})
</insert>最終耗時(shí):14s多

二.關(guān)閉MySql自動(dòng)提交,手動(dòng)進(jìn)行循環(huán)插入提交
@RestController
@RequestMapping("/mybatis3/user")
@RequiredArgsConstructor
public class UserController {
private final IUserService iUserService;
@GetMapping("/one")
public Long one(){
return iUserService.add();
}
}
Long add2();
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
private final UserMapper userMapper;
// 手動(dòng)開啟sql的批量提交
private final SqlSessionTemplate sqlSessionTemplate;
@Override
public Long add2(){
//關(guān)閉自動(dòng)提交
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
User user = new User();
user.setUsername("name"+i);
user.setPassword("password"+i);
mapper.insertUsers(user);
}
//自動(dòng)提交SQL
sqlSession.commit();
long end = System.currentTimeMillis();
System.out.println("耗時(shí):"+( end - start ) + "ms");
return (end-start);
}
}平均:0.12s

第三種:用List集合的方式插入數(shù)據(jù)庫(推薦)
@RestController
@RequestMapping("/mybatis3/user")
@RequiredArgsConstructor
public class UserController {
private final IUserService iUserService;
@GetMapping("/one3")
public Long one3(){
return iUserService.add3();
}
}
Long add3();
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
private final UserMapper userMapper;
@Override
public Long add3(){
long start = System.currentTimeMillis();
List<User> userList = new ArrayList<>();
User user;
for (int i = 0; i < 10000; i++) {
user = new User();
user.setUsername("name"+i);
user.setPassword("password"+i);
userList.add(user);
}
userMapper.insertUsersThree(userList);
long end = System.currentTimeMillis();
System.out.println("耗時(shí):"+( end - start ) + "ms");
return (end-start);
}
}
Integer insertUsersThree(List<User> userList);
<insert id="insertUsersThree">
insert into user(username,password)
values
<foreach collection="userList" item="user" separator=",">
(#{user.username},#{user.password})
</foreach>
</insert>第四種: MyBatis-Plus提供的SaveBatch方法
@RestController
@RequestMapping("/mybatis3/user")
@RequiredArgsConstructor
public class UserController {
private final IUserService iUserService;
@GetMapping("/one4")
public Long one4(){
return iUserService.add4();
}
}
Long add4();
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
private final UserMapper userMapper;
@Override
public Long add4() {
long start = System.currentTimeMillis();
List<User> userList= new ArrayList<>();
User user ;
for (int i = 0; i < 10000; i++) {
user = new User();
user.setUsername("name"+i);
user.setPassword("password"+i);
userList.add(user);
}
saveBatch(userList);
long end = System.currentTimeMillis();
System.out.println("耗時(shí):"+( end - start ) + "ms");
return (end-start);
}
}直接報(bào)錯(cuò):

看報(bào)錯(cuò)信息:
長串:Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: com.huang.mybatis3.mapper.UserMapper.insert (batch index #1) failed. Cause: java.sql.BatchUpdateException: Data truncation: Out of range value for column ‘id’ at row 1
; Data truncation: Out of range value for column ‘id’ at row 1; nested exception is java.sql.BatchUpdateException: Data truncation: Out of range value for column ‘id’ at row 1] with root cause短串:Data truncation: Out of range value for column ‘id’ at row 1
翻譯一下:

可以發(fā)現(xiàn)就是我們的id超出范圍:

int類型改為bigint即可
故此我們可以得出一個(gè)結(jié)論:設(shè)置數(shù)據(jù)庫id的時(shí)候設(shè)置為bigint還是蠻好的哈
平均時(shí)間:0.2s

第五種 MyBatis-Plus提供的InsertBatchSomeColumn方法(推薦)
InsertBatchSomeColumn方法了解

這個(gè)類的注解就寫的很明白
擴(kuò)展這個(gè)InsertBatchSomeColumn方法
@Slf4j
public class EasySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// 注意:此SQL注入器繼承了DefaultSqlInjector(默認(rèn)注入器),調(diào)用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自帶方法
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
log.info("擴(kuò)展的getMethodList方法被框架調(diào)用了");
return methodList;
}
}擴(kuò)展的方法注入bean容器
/**
* @author Stone
* @date 2023/1/3
* @apiNote
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public EasySqlInjector sqlInjector(){
return new EasySqlInjector();
}
}創(chuàng)建一個(gè)Mapper去實(shí)現(xiàn)我們的擴(kuò)展的飛方法
public interface EasySqlInjectMapper<T> extends BaseMapper<T> {
/**
* 批量插入 僅適用于mysql
*
* @param entityList 實(shí)體列表
* @return 影響行數(shù)
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
業(yè)務(wù)層
@Override
public Long add5() {
long start = System.currentTimeMillis();
List<User> userList= new ArrayList<>();
User user ;
for (int i = 0; i < 10000; i++) {
user = new User();
user.setUsername("name"+i);
user.setPassword("password"+i);
userList.add(user);
}
userMapper.insertBatchSomeColumn(userList);
long end = System.currentTimeMillis();
System.out.println("耗時(shí):"+( end - start ) + "ms");
return (end-start);
}耗時(shí): 0.2 s

總結(jié)
到此這篇關(guān)于MyBatis的五種批量查詢的文章就介紹到這了,更多相關(guān)MyBatis批量查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Spring Boot 項(xiàng)目啟動(dòng)時(shí)執(zhí)行特定方法
這篇文章主要介紹了詳解Spring Boot 項(xiàng)目啟動(dòng)時(shí)執(zhí)行特定方法,Springboot給我們提供了兩種“開機(jī)啟動(dòng)”某些方法的方式:ApplicationRunner和CommandLineRunner。感興趣的小伙伴們可以參考一下2018-06-06
java 中使用maven shade plugin 打可執(zhí)行Jar包
這篇文章主要介紹了java 中使用maven shade plugin 打可執(zhí)行Jar包的相關(guān)資料,需要的朋友可以參考下2017-05-05
Java項(xiàng)目在Idea中開發(fā)遇到所有代碼爆紅的問題與解決辦法
今天打開項(xiàng)目時(shí)發(fā)現(xiàn)idea竟然爆紅,通過查找相關(guān)資料用于解決,下面這篇文章主要給大家介紹了關(guān)于Java項(xiàng)目在Idea中開發(fā)遇到所有代碼爆紅的問題與解決辦法的相關(guān)資料,需要的朋友可以參考下2023-06-06
Java?多線程并發(fā)?ReentrantReadWriteLock詳情
這篇文章主要介紹了Java多線程并發(fā)ReentrantReadWriteLock詳情,ReentrantReadWriteLock可重入讀寫鎖。實(shí)際使用場景中,我們需要處理的操作本質(zhì)上是讀與寫,更多相關(guān)資料,感興趣的小伙伴可以參考一下下面文章內(nèi)容2022-06-06
Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來的
這篇文章主要介紹了Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
用java實(shí)現(xiàn)的獲取優(yōu)酷等視頻縮略圖的實(shí)現(xiàn)代碼
想獲取優(yōu)酷等視頻縮略圖,在網(wǎng)上沒有找到滿意的資料,參考了huangdijia的PHP版工具一些思路,寫了下面的JAVA版代碼。。其實(shí)也可以做成JS版的2013-05-05
IDEA配置Tomcat創(chuàng)建web項(xiàng)目的詳細(xì)步驟
Tomcat是一個(gè)Java?Web應(yīng)用服務(wù)器,實(shí)現(xiàn)了多個(gè)Java?EE規(guī)范(JSP、Java?Servlet等),這篇文章主要給大家介紹了關(guān)于IDEA配置Tomcat創(chuàng)建web項(xiàng)目的詳細(xì)步驟,需要的朋友可以參考下2023-12-12
java實(shí)現(xiàn)銀行家算法(Swing界面)
這篇文章主要為大家詳細(xì)介紹了銀行家算法的java代碼實(shí)現(xiàn),Swing寫的界面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12

