平时记录一些自己工作日常中用到的工具,可以方便下次快速复用。
下面方法涉及对象转换map,对象集合转insert脚本集合,获取到该集合后直接写入到指定文件就行了
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public static <T> List<String> getInsertSql(List<T> list, String table) {
if (!CollectionUtils.isEmpty(list)) {
List<String> results = new ArrayList<>();
for (T t : list) {
try {
Map<String, Object> map = beanToMap(t);
StringBuffer head = new StringBuffer("INSERT INTO `" + table + "` ( ");
StringBuffer end = new StringBuffer(" ) VALUES ( ");
for (String key : map.keySet()) {
head.append(" `" + key + "`,");
Object val = map.get(key);
if (val == null) {
end.append(" null , ");
} else {
if (val instanceof BigDecimal) {
BigDecimal b = new BigDecimal(val.toString());
if (b != null) {
b = b.setScale(2, BigDecimal.ROUND_HALF_DOWN);
} else {
b = BigDecimal.ZERO;
}
end.append(" '" + b.floatValue() + "', ");
} else if (val instanceof Date) {
Date b = (Date) val;
end.append(" '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(b) + "', ");
} else {
end.append(" '" + val.toString() + "', ");
}
}
}
String result = head.toString();
result = result.substring(0, result.length() - 1);
String ttt = end.toString();
result = result + ttt.substring(0, ttt.length() - 2) + " ); ";
results.add(result);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return results;
}
return null;
}
public static Map<String, Object> beanToMap(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}