1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map;
@SuppressWarnings("all") public class SqlBuildUtil {
protected static Logger logger = Logger.getLogger(SqlBuildUtil.class);
public static Map batchInsert(List sourceList, Class clazz) throws Exception { List list = new ArrayList<>(); sourceList.stream().forEach(o -> { try { Object obj = Class.forName(clazz.getName()).newInstance(); BeanUtils.setBean(obj, BeanUtils.bean2Map(o)); list.add(obj); } catch (Exception e) { e.printStackTrace(); } }); String tableName = clazz.getSimpleName(); List<Field> fieldList = Arrays.asList(clazz.getDeclaredFields()); StringBuilder sql = new StringBuilder(); StringBuilder keySb = new StringBuilder("INSERT INTO"); keySb.append(" `").append(tableName).append("` "); keySb.append(" ("); int fieldLength = fieldList.size(); for (int i = 0; i < fieldLength; i++) { Field field = fieldList.get(i); keySb.append("`").append(field.getName()).append("`"); if (i != fieldLength - 1) { keySb.append(","); } } keySb.append(") ").append("VALUES"); int listSize = list.size(); for (int i = 0; i < listSize; i++) { StringBuilder valSb = new StringBuilder(); valSb.append(" ("); for (int j = 0; j < fieldLength; j++) { Field field = fieldList.get(j); field.setAccessible(true); Object val = field.get(list.get(i)); if (String.class.equals(field.getType())) { valSb.append("'").append(ObjectUtils.isEmpty(val) ? "" : val).append("'"); } else { valSb.append(ObjectUtils.isEmpty(val) ? 0 : val); } if (j != fieldLength - 1) { valSb.append(","); } } valSb.append(");\n"); sql.append(keySb).append(valSb); logger.info("构造表名为 " + tableName + " 的恢复数据量为 " + listSize + " 条,SQL:\n" + sql.toString()); } return MapUtils.toMap(new Object[][]{ {"sql", sql}, {"count", listSize}, }); }
}
|