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(); } }); }