欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatisplus添加真正的批量新增、批量更新的实现

程序员文章站 2022-03-24 08:29:04
使用mybatis-plus来进行批量新增和更新时,你会发现其实是一条条sql执行,下面进行优化。1.添加insertbatchmethod和updatebatchmethod类import com....

使用mybatis-plus来进行批量新增和更新时,你会发现其实是一条条sql执行,下面进行优化。

1.添加insertbatchmethod和updatebatchmethod类

import com.baomidou.mybatisplus.core.injector.abstractmethod;
import com.baomidou.mybatisplus.core.metadata.tableinfo;
import lombok.extern.slf4j.slf4j;
import org.apache.ibatis.executor.keygen.nokeygenerator;
import org.apache.ibatis.mapping.mappedstatement;
import org.apache.ibatis.mapping.sqlsource;
 
/**
 * 批量插入方法实现
 */
@slf4j
public class insertbatchmethod extends abstractmethod {
  @override
  public mappedstatement injectmappedstatement(class<?> mapperclass, class<?> modelclass, tableinfo tableinfo) {
    final string sql = "<script>insert into %s %s values %s</script>";
    final string fieldsql = preparefieldsql(tableinfo);
    final string valuesql = preparevaluessql(tableinfo);
    final string sqlresult = string.format(sql, tableinfo.gettablename(), fieldsql, valuesql);
    //log.debug("sqlresult----->{}", sqlresult);
    sqlsource sqlsource = languagedriver.createsqlsource(configuration, sqlresult, modelclass);
    return this.addinsertmappedstatement(mapperclass, modelclass, "insertbatch", sqlsource, new nokeygenerator(), null, null);
  }
 
  private string preparefieldsql(tableinfo tableinfo) {
    stringbuilder fieldsql = new stringbuilder();
    fieldsql.append(tableinfo.getkeycolumn()).append(",");
    tableinfo.getfieldlist().foreach(x -> fieldsql.append(x.getcolumn()).append(","));
    fieldsql.delete(fieldsql.length() - 1, fieldsql.length());
    fieldsql.insert(0, "(");
    fieldsql.append(")");
    return fieldsql.tostring();
  }
 
  private string preparevaluessql(tableinfo tableinfo) {
    final stringbuilder valuesql = new stringbuilder();
    valuesql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
    valuesql.append("#{item.").append(tableinfo.getkeyproperty()).append("},");
    tableinfo.getfieldlist().foreach(x -> valuesql.append("#{item.").append(x.getproperty()).append("},"));
    valuesql.delete(valuesql.length() - 1, valuesql.length());
    valuesql.append("</foreach>");
    return valuesql.tostring();
  }
}
import com.baomidou.mybatisplus.core.injector.abstractmethod;
import com.baomidou.mybatisplus.core.metadata.tableinfo;
import lombok.extern.slf4j.slf4j;
import org.apache.ibatis.mapping.mappedstatement;
import org.apache.ibatis.mapping.sqlsource;
 
/**
 * 批量更新方法实现,条件为主键,选择性更新
 */
@slf4j
public class updatebatchmethod extends abstractmethod {
  @override
  public mappedstatement injectmappedstatement(class<?> mapperclass, class<?> modelclass, tableinfo tableinfo) {
    string sql = "<script>\n<foreach collection=\"list\" item=\"item\" separator=\";\">\nupdate %s %s where %s=#{%s} %s\n</foreach>\n</script>";
    string additional = tableinfo.iswithversion() ? tableinfo.getversionfieldinfo().getversionoli("item", "item.") : "" + tableinfo.getlogicdeletesql(true, true);
    string setsql = sqlset(tableinfo.iswithlogicdelete(), false, tableinfo, false, "item", "item.");
    string sqlresult = string.format(sql, tableinfo.gettablename(), setsql, tableinfo.getkeycolumn(), "item." + tableinfo.getkeyproperty(), additional);
    //log.debug("sqlresult----->{}", sqlresult);
    sqlsource sqlsource = languagedriver.createsqlsource(configuration, sqlresult, modelclass);
    // 第三个参数必须和rootmapper的自定义方法名一致
    return this.addupdatemappedstatement(mapperclass, modelclass, "updatebatch", sqlsource);
  } 
}

2.添加自定义方法sql注入器

import com.baomidou.mybatisplus.core.injector.abstractmethod;
import com.baomidou.mybatisplus.core.injector.defaultsqlinjector;
 
import java.util.list;
 
public class customizedsqlinjector extends defaultsqlinjector {
  /**
   * 如果只需增加方法,保留mybatis plus自带方法,
   * 可以先获取super.getmethodlist(),再添加add
   */
  @override
  public list<abstractmethod> getmethodlist(class<?> mapperclass) {
    list<abstractmethod> methodlist = super.getmethodlist(mapperclass);
    methodlist.add(new insertbatchmethod());
    methodlist.add(new updatebatchmethod());
    return methodlist;
  }
}

3.注入配置

@mapperscan("com.xxx.mapper")
@configuration
public class mybatisplusconfig {
  @bean
  public customizedsqlinjector customizedsqlinjector() {
    return new customizedsqlinjector();
  }
}

4.添加通用mapper

import com.baomidou.mybatisplus.core.mapper.basemapper;
import org.apache.ibatis.annotations.param;
 
import java.util.list;
 
/**
 * 根mapper,给表mapper继承用的,可以自定义通用方法
 * {@link com.baomidou.mybatisplus.core.mapper.basemapper}
 * {@link com.baomidou.mybatisplus.extension.service.iservice}
 * {@link com.baomidou.mybatisplus.extension.service.impl.serviceimpl}
 */
public interface rootmapper<t> extends basemapper<t> {
 
  /**
   * 自定义批量插入
   * 如果要自动填充,@param(xx) xx参数名必须是 list/collection/array 3个的其中之一
   */
  int insertbatch(@param("list") list<t> list);
 
  /**
   * 自定义批量更新,条件为主键
   * 如果要自动填充,@param(xx) xx参数名必须是 list/collection/array 3个的其中之一
   */
  int updatebatch(@param("list") list<t> list);
}

5.如何使用

@repository
public interface userinfomapper extends rootmapper<userinfo> {
} 
 
public interface userinfoservice extends iservice<userinfo> { 
  int saveall(); 
  int updateall();
}
 
@service
public class userinfoserviceimpl extends serviceimpl<userinfomapper, userinfo> implements userinfoservice{
 
  @override
  public int saveall() {
    list<userinfo> list = new arraylist<>();
    for (int i = 0; i < 20; i++) {
      userinfo userinfo = new userinfo();
      userinfo.setusername("厉害" + i);
      userinfo.setsalt(randomstringutils.randomalphabetic(6));
      userinfo.setpassword(secureutil.sha256("123456" + userinfo.getsalt()));
      userinfo.setsex(0);
      userinfo.setavatar(loginserviceimpl.avatar);
      list.add(userinfo);
    }
    return basemapper.insertbatch(list);
  }
 
  @override
  public int updateall() {
    list<userinfo> userinfos = basemapper.selectlist(wrappers.<userinfo>lambdaquery().between(baseentity::getid, 43, 62));
    userinfos.foreach(userinfo -> {
      userinfo.setusername("更新了" + idutil.simpleuuid());
    });
    return basemapper.updatebatch(userinfos);
  }
}

到此这篇关于mybatisplus添加真正的批量新增、批量更新的实现的文章就介绍到这了,更多相关mybatisplus批量新增、批量更新内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!