springBoot 封装jdbc批量新增接口

jdbc 提供原生批量操做batchUpdata 方法,可是使用起来很是不便须要咱们本身实现PreparedStatement来设置字段位置、名称及属性。如下是本人根据类的抽象特性对jdbc批量操做作了封装,有什么不足欢迎指出html

protected  void saveAll(List<T> t, Object cz, String tablename){
        Map<String,String> parameterType=new HashMap<>();
        String condition = DataUtils.buildInsertSqlCondition(cz, parameterType);
        String sql = "insert into " + tablename + condition;
        gbiapJdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                T cz = t.get(i);
                int index=1;
                for (Map.Entry<String,String> entry:parameterType.entrySet()    ) {
                    String name = entry.getKey();
                    String type = entry.getValue();
                    name=name.substring(0,1).toUpperCase()+name.substring(1);//首字母变大
                    try {
                        Method method = cz.getClass().getMethod("get" + name);
                        switch (type){
                            case "java.lang.String":
                                ps.setString(index,(String)method.invoke(cz));
                                index++;
                                break;
                            case "float":
                                ps.setFloat(index,(float)method.invoke(cz));
                                index++;
                                break;
                            case "int":
                                ps.setInt(index,(int)method.invoke(cz));
                                index++;
                                break;
                            case "long":
                                ps.setLong(index,(long)method.invoke(cz));
                                index++;
                                break;
                            case "double":
                                ps.setDouble(index,(double)method.invoke(cz));
                                index++;
                                break;
                            default:
                                ps.setString(index,(String)method.invoke(cz));
                                index++;
                                break;
                        }
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            @Override
            public int getBatchSize() {
                return t.size();
            }
        });
    }

 

 

 

相关文章
相关标签/搜索