JAVA创建临时表
public boolean insertTempTableData(String tableName, List<Map<String, String>> records) {
boolean success = false;
try {
tableName = StringUtils.prependIfMissingIgnoreCase(tableName, "temp_", "temp_");//在字符串的最左边插入一个指定字符,如果已存在则不插入,返回字符串;方法末尾带Case表示不区分大小写
if (CollectionUtils.isNotEmpty(records)) {//判断数组是否为空
Map<String, String> header = records.stream().findAny().orElse(Collections.emptyMap());//findAny():返回任意一个;orElse():如果一个都没有找到就返回()
if (MapUtils.isNotEmpty(header)) {
List<String> columns = header.keySet().stream().collect(Collectors.toList());//map.keySet()返回Set<String>, stream().collect(Collectors.toList())转换成数组
if (createTempTable(tableName, columns)) {//创建临时表表
List<Map<String, String>> temp = records;
SQL sqlTemplate = new SQL();//sql模板
sqlTemplate.INSERT_INTO(tableName);//表名
sqlTemplate.INTO_COLUMNS(columns.toArray(new String[]{}));//列
sqlTemplate.INTO_VALUES(columns.stream().map(name -> StringUtils.join(":", name)).toArray(String[]::new));//值 变量
while (temp.size() > 100000) {
List<Map<String, String>> subList = temp.subList(0, 100000);
batchUpdate(sqlTemplate, subList);
temp = temp.subList(100000, temp.size());
}
if (CollectionUtils.isNotEmpty(temp)) {
batchUpdate(sqlTemplate, temp);//写入数据
}
success = true;
}
}
}
} catch (Exception e) {
log.warn("插入临时表{}失败:{}", tableName, e.getMessage());
}
return success;
}
pom文件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
SQL
<update id="createTempTable">
CREATE GLOBAL TEMPORARY TABLE ${tableName}
<foreach collection="columns" item="column" index="index" open="(" close=")" separator=",">
${column} VARCHAR2(2048)
</foreach>
ON COMMIT DELETE ROWS
</update>
摘抄自网络,便于检索查找。