• mybatis批量提交


    之前在做项目时,使用mybatis,批量执行sql,这里简单写下步骤

    • 在配置数据库连接时,加入一个参数,例如

    jdbc:mysql://127.0.0.1:3307/mvs-report?allowMultiQueries=true

    • 在mybatis执行时传入list集合参数,
    • 在mybatis的xml文件中拼装sql,例如
    <insert id="batchInsert" parameterType="java.util.List" >
        insert into rpt_fault (FAULT_ID, FAULT_NAME)
        values 
        <foreach collection="list" item="item" separator=",">
            (#{item.faultId,jdbcType=INTEGER}, #{item.faultName,jdbcType=VARCHAR})
        </foreach>
      </insert>
    • 一般来说这就满足需求了,但是为了更好的扩展,最好是指定一个集合最大值,这样一来方便在不同配置的服务器上切换,手动调节阈值。本示例使用了java反射特性来实现,具体如下
       1     private static final int ADD_MAX = 200;
       2     private static final int DELETE_MAX = 500;
       3     public static void executeBatchAdd(Object mapper, List<?> list) throws Exception {
       4         if (Objects.isNull(list) || list.isEmpty())
       5             return;
       6 
       7         try {
       8             Method method = mapper.getClass().getMethod("batchInsert", List.class);
       9             int size = list.size();
      10             if (size > ADD_MAX) {
      11                 int num = (size) / ADD_MAX + 1;
      12                 int start = 0, end = 0;
      13                 for (int i = 1; i <= num; i++) {
      14                     start = (i - 1) * ADD_MAX;
      15                     end = (i * ADD_MAX) > size ? size : (i * ADD_MAX);
      16                     method.invoke(mapper, list.subList(start, end));
      17                 }
      18             } else
      19                 method.invoke(mapper, list);
      20         } catch (Exception e) {
      21             logger.error("批量插入任务执行失败:", e.getMessage(), e);
      22             throw e;
      23         } finally {
      24             list.clear();
      25         }
      26     }

       最后补充:

    • 有时候我们在使用mysql数据库时候,当我们的阈值过大时,可能会遇到过more than 'max_binlog_cache_size' bytes of storage 的错误
    • 这是不要慌,这是mysql默认的日志提交字节太小导致的。
    • 首先查看当前设置的大小:show variables like '%binlog_%size%';
    • 然后酌情设置set global max_binlog_cache_size=10737418240;
    • 此种方式不用重启数据库服务器,较为简便。
  • 相关阅读:
    (一)Python装饰器的通俗理解
    Linux实例安装VNC Server实现图形化访问
    TightVNC for Windows
    使用Xmanager远程CentOS 7服务器(XDMCP)
    Using Xmanager to connect to remote CentOS 7 via XDMCP
    在windows上使用xdmcp登陆centos,红帽linux
    Xmanger远程连接Centos7(成功配置)
    Centos7.2命令安装图形化界面
    CentOS 7安装图形界面
    CentOS 7命令行安装GNOME、KDE图形界面(成功安装验证)
  • 原文地址:https://www.cnblogs.com/songyz/p/mybatis.html
Copyright © 2020-2023  润新知