记录一种大数据修改或者删除的sql批量分大小执行优化的方法
首先需要注入entitymanager对象
@PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager entityManager;
实际代码如下
List<String> userList= new ArrayList<>();
StringBuffer sqlAppend = new StringBuffer();
List<String> arrList = new ArrayList<>();
userList.add("张三");
userList.add("李四");
userList.add("王五");
···
for (String userName : userList) {
HashMap map = new HashMap();
map.put("ID",UUID.randomUUID().toString())
map.put("NAME",userName )
String sqlInsert = insertFromMapOfItem(map, "USERINFO");
if (!"".equals(sqlInsert)) {
arrList.add(sqlInsert);
}
}
long sqlCount = 0;
int sqlRunCount = 1000;
Map<String, String> sqlMap = new HashMap<String, String>();
for (String sql : arrList) {
sqlAppend.append(sql);
sqlCount++;
if (sqlCount == sqlRunCount) {
sqlMap.put(String.valueOf(sqlMap.size() + 1), sqlAppend.toString());
sqlAppend.setLength(0);
sqlCount = 0;
}
}
if (sqlAppend.length() != 0) {
sqlMap.put(String.valueOf(sqlMap.size() + 1), sqlAppend.toString());
sqlAppend.setLength(0);
sqlCount = 0;
}
for (String key : sqlMap.keySet()) {
entityManager.createNativeQuery(sqlMap.get(key)).executeUpdate();
}
将map转换为插入sql的方法如下。有条件的话其实可以使用JPA的实体批量保存
或者批量删除方法,批量保存用saveAll、删除用deleteAll()或者
deleteAllInBatch(),
区别是deleteAll()是删除全部,先找出所有再一条一条的删除,
最后再提交事务。deleteAllInBatch()是一次性删除全部,当然用后者效率更高
public String insertFromMapOfItem(HashMap<String, Object> map, String tablename) {
ArrayList<Object> arrKey = new ArrayList<>();
ArrayList<Object> arrValue = new ArrayList<>();
for (String key : map.keySet()) {
arrKey.add(key);
}
for (String keys : map.keySet()) {
arrValue.add(map.get(keys));
}
StringBuffer strKey = new StringBuffer();
StringBuffer strVal = new StringBuffer();
for (int j = 0; j < arrKey.size(); j++) {
strKey.append(arrKey.get(j));
if (j != arrKey.size() - 1) {
strKey.append(",");
}
}
for (int j = 0; j < arrValue.size(); j++) {
if (null != arrValue.get(j) && !"".equals(arrValue.get(j))) {
strVal.append("'" + arrValue.get(j) + "'");
} else if ("".equals(arrValue.get(j))) {
strVal.append("" + null + "");
} else {
strVal.append(arrValue.get(j));
}
if (j != arrValue.size() - 1) {
strVal.append(",");
}
}
String stringEntryKey = strKey.toString();
String stringEntryVal = strVal.toString();
String sqlEntry = "INSERT INTO " + tablename + " (" + stringEntryKey + ") VALUES (" + stringEntryVal + ");";
return sqlEntry;
}
|