mybatis-plus批量insert效率低下怎么办(mysql)

mybatis-plus批量insert效率低下怎么办

(数据库是mysql的情况下)

mybatis-plus的顶级IService接口有一个saveBatch()方法,
但是它会执行多条insertSql,
在数据量大的时候效率会非常差,

如果我们是mysql数据库,又不想自己写mapper.xml,
mybatis-plus提供了InsertBatchSomeColumn批量insert方法,
需要我们自己注入下。

1、继承DefaultSqlInjector

package com.superv.message.common.mybatisplus;

import java.util.List;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;

public class EasySqlInjector extends DefaultSqlInjector {

	@Override
	public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
		// TODO Auto-generated method stub
		List<AbstractMethod> methodList = super.getMethodList(mapperClass);
		methodList.add(new InsertBatchSomeColumn()); // 添加InsertBatchSomeColumn方法
		return methodList;
	}
	
}

2、注入到spring容器

package com.superv.message.common.mybatisplus;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class MybatisPlusConfig {

	@Bean
	public EasySqlInjector easySqlInjector () {
		return new EasySqlInjector();
	}
	
}

3、在我们的mapper.java中这样

package com.superv.message.mapper;

import java.util.Collection;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.superv.message.entity.Message;

@Mapper
public interface MessageMapper extends BaseMapper<Message> {

	/**
	 * 批量插入(mysql)
	 * @param entityList
	 * @return
	 */
	Integer insertBatchSomeColumn(Collection<Message> entityList);
	
}

不需要再去写mapper.xml,直接调用这个方法就可以批量保存了,

它是这样执行的:
insert into table values (x1, y1, z1), (x2, y2, z2), (x…, y…, z…);

参考资料:

盛夏温暖流年Mybatis Plus 实现批量插入
Java旺给你的MyBatis-Plus装上批量插入的翅膀

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值