Springboot jdbcTemplete一次连接插入多条数据

前端给我传List集合数据,按常理需要循环调用service保存接口,但是我想循环连库操作觉得还是挺浪费的,就想有没有批量查询的,然后就发现mysql可以这样一次插入多条

insert into 表名 (字段)  values ('数据'),('数据');

这样就可以一次连接一张表进行多次插入了。

那因为前端传的数据是不固定的,有可能传4个需要保存的,有可能传5个,甚至更多,所以使用插入多条一定要把库里所有的字段都写上,values最重要的是要与字段一一对应。

我采用反射将实体上的字段改成数据库的字段,然后将库里所有的字段以集合返回,这时候集合的顺序和实体属性顺序是一样的,然后循环遍历前端传过来的值数据,因为实体顺序是一样的,所以直接按实体顺序进行判断拼接值,得到插入多条的sql语句

拼接sql语句代码如下

 /**
     * 生成批量的insertSql语句
     *
     * @param adressList
     * @param dcid
     * @return
     */
    public String createBatchSql(List<RegisteredKjResourceadress> adressList, Long dcid) {
        Object2MapConfig mapConfig = new Object2MapConfig();
        mapConfig.setIsPrimaryKey(false);
        mapConfig.setPrimaryKey("ID");
        StringBuffer str = new StringBuffer("insert into 表名 (");
        StringBuffer totalValue = new StringBuffer(" values ");
        if (adressList.size() > 0) {
            // 获取字段
            List<String> filedList = EntityToMap.object2MapNullFiled(adressList.get(0), mapConfig);
            for (String filedName : filedList) {
                if (str.length() == 43) {
                    str.append(filedName);
                } else {
                    str.append("," + filedName);
                }
            }
            if (str.length() > 43) {
                str.append(")");
            }
            // 获取数据值,注意与字段数组一一对应,字段数组是和实体顺序一一对应
            for (int i = 0; i < adressList.size(); i++) {
                StringBuffer strValue = new StringBuffer("");
                RegisteredKjResourceadress resourceadress = adressList.get(i);
                if (dcid != 0) {
                    resourceadress.setDcid(dcid);
                }
                String nowTime = TimeUtil.getNowTime();
                resourceadress.setCreateTime(nowTime);
                if (resourceadress.getDcid() != null && !resourceadress.getDcid().equals("")) {
                    if (strValue.length() == 0) {
                        strValue.append("(" + resourceadress.getDcid());
                    } else {
                        strValue.append("," + resourceadress.getDcid());
                    }
                } else {
                    if (strValue.length() == 0) {
                        strValue.append("(0");
                    } else {
                        strValue.append(",0");
                    }
                }
                if (resourceadress.getDcaddress() != null && !resourceadress.getDcaddress().equals("")) {
                    if (strValue.length() == 0) {
                        strValue.append("('" + resourceadress.getDcaddress() + "'");
                    } else {
                        strValue.append(",'" + resourceadress.getDcaddress() + "'");
                    }
                } else {
                    if (strValue.length() == 0) {
                        strValue.append("(''");
                    } else {
                        strValue.append(",''");
                    }
                }
                if (resourceadress.getServiceName() != null && !resourceadress.getServiceName().equals("")) {
                    if (strValue.length() == 0) {
                        strValue.append("('" + resourceadress.getServiceName() + "'");
                    } else {
                        strValue.append(",'" + resourceadress.getServiceName() + "'");
                    }
                } else {
                    if (strValue.length() == 0) {
                        strValue.append("(''");
                    } else {
                        strValue.append(",''");
                    }
                }

                if (resourceadress.getRemark() != null && !resourceadress.getRemark().equals("")) {
                    if (strValue.length() == 0) {
                        strValue.append("('" + resourceadress.getRemark() + "'");
                    } else {
                        strValue.append(",'" + resourceadress.getRemark() + "'");
                    }
                } else {
                    if (strValue.length() == 0) {
                        strValue.append("(''");
                    } else {
                        strValue.append(",''");
                    }
                }

                if (resourceadress.getInterfaceType() != null && !resourceadress.getInterfaceType().equals("")) {
                    if (strValue.length() == 0) {
                        strValue.append("('" + resourceadress.getInterfaceType() + "'");
                    } else {
                        strValue.append(",'" + resourceadress.getInterfaceType() + "'");
                    }
                } else {
                    if (strValue.length() == 0) {
                        strValue.append("(''");
                    } else {
                        strValue.append(",''");
                    }
                }

                if (strValue.length() == 0) {
                    strValue.append("('" + resourceadress.getCreateTime() + "'");
                } else {
                    strValue.append(",'" + resourceadress.getCreateTime() + "'");
                }


                if (strValue.length() > 0) {
                    strValue.append(")");
                }
                if (adressList.size() >= 2 && (i + 1) != adressList.size()) {
                    strValue.append(",");
                }
                if ((i + 1) == adressList.size()) {
                    strValue.append(";");
                }
                totalValue.append(strValue);
            }
            if (totalValue.length() > 1 && str.length() > 43) {
                String sql = str.append(totalValue) + "";
                return sql;
            }
        }
        return null;

    }

Object2MapConfig属性配置

public class Object2MapConfig {
    /**
     * 主键是否参与语句生成; true=是;false=否
     */
    private boolean isPrimaryKey;
    /**
     * 主键字段
     */
    private String primaryKey;

    public boolean isPrimaryKey() {
        return isPrimaryKey;
    }

    public void setIsPrimaryKey(boolean isPrimaryKey) {
        isPrimaryKey = isPrimaryKey;
    }

    public String getPrimaryKey() {
        return primaryKey;
    }

    public void setPrimaryKey(String primaryKey) {
        this.primaryKey = primaryKey;
    }
}
EntityToMap.object2MapNullFiled方法
/**
     * list数组形式返回字段名称
     *
     * @param obj
     * @param object2MapConfig
     * @return
     */
    public static List<String> object2MapNullFiled(Object obj, Object2MapConfig object2MapConfig) {
        List<String> list = new ArrayList<>();
        if (obj == null) {
            return null;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                // !field.get(obj).equals("") &&
                // 满足条件:key不为空,key不为序列条件
                System.out.println(obj);
                if (!field.getName().equals("serialVersionUID")) {
                    // 正则查找大写字母往后移一格,替换_最后转大写
                    String strUpperCase = field.getName().replaceAll("[A-Z]", " $0")
                            .replace(" ", "_").toUpperCase();
                    if (object2MapConfig.isPrimaryKey() == false) {
                        if (strUpperCase.equals(object2MapConfig.getPrimaryKey())) {
                        } else {
                            list.add(strUpperCase);
                        }
                    } else {
                        list.add(strUpperCase);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

最后sql语句也生成了,就要插入操作了

 public Boolean saveResourceAddress(List<RegisteredKjResourceadress> resourceadress, Long dcid) {
        String sql = createBatchSql(resourceadress, dcid);
        try {
            if (sql != null) {
                int num = jdbcTemplate.update(sql);
                return true;
            }
        } catch (Exception e) {
            log.debug("insert err! SQL Statement Is:{}", sql);
            e.printStackTrace();
            return false;
        }
        return null;
    }

 亲测可用!希望可以帮助你!

猜你喜欢

转载自blog.csdn.net/dfBeautifulLive/article/details/105856511