import cn.hutool.core.util.StrUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import com.alibaba.fastjson.JSON;
import groovy.lang.GroovyClassLoader;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 操作数据表工具类
*/
@Slf4j
public class TableUtil {
/**
* 判断表已经存在
*
* @param dataSource 数据源
* @param tableName 表名
* @return
*/
public static boolean isTableExist(DataSource dataSource, String tableName) {
String sql = "SELECT table_name FROM information_schema.TABLES ";
List<Entity> list = sqlExecutorSelect(dataSource, sql);
if (list == null) {
return false;
}
for (Entity entity : list) {
if (tableName.equalsIgnoreCase(entity.get("TABLE_NAME") + "")) {
return true;
}
}
return false;
}
/**
* SQL执行器-非查询
*/
public static Integer sqlExecutor(DataSource dataSource, String sql) {
Connection conn = null;
try {
conn = dataSource.getConnection();
return SqlExecutor.execute(conn, sql);
} catch (SQLException e) {
log.error("SQL error!");
log.error("错误SQL:"+sql);
} finally {
DbUtil.close(conn);
}
return null;
}
/**
* SQL执行器非-查询
*/
public static List<Entity> sqlExecutorSelect(DataSource dataSource, String sql, Object... params) {
Connection conn = null;
try {
conn = dataSource.getConnection();
/* 执行查询语句,返回实体列表,一个Entity对象表示一行的数据,Entity对象是一个继承自HashMap的对象,存储的key为字段名,value为字段值 */
return SqlExecutor.query(conn, sql, new EntityListHandler(), params);
} catch (SQLException e) {
log.error("SQL error!");
} finally {
DbUtil.close(conn);
}
return null;
}
/**
* 根据表名生成实体类
*
* @param className 雷鸣
* @param columns 字段信息(字段名,字段类型)
* @return
*/
@SneakyThrows
public static Class<?> createClass(String className, Map<String, String> columns) {
String temp = " private {v} {k};\n" +
" \n" +
" public {v} get{K}() {\n" +
" return {k};\n" +
" }\n" +
" public void set{K}({v} id) {\n" +
" this.{k} = {k};\n" +
" }\n";
//拼接字段
ArrayList<String> list = new ArrayList<>();
columns.forEach((k, v) -> {
HashMap<String, String> map = new HashMap<>();
map.put("v", v);
map.put("k", k);
map.put("K", StrUtil.upperFirst(k));
list.add(StrUtil.format(temp, map));
});
//groovy提供了一种将字符串文本代码直接转换成Java Class对象的功能
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
//里面的文本是Java代码,但是我们可以看到这是一个字符串我们可以直接生成对应的Class<?>对象,而不需要我们写一个.java文件
Class<?> clazz = groovyClassLoader.parseClass("package com.ciih.workshop.entity;\n" +
"import java.util.Date;\n" +
"\n" +
"public class " + className + " {\n" +
"\n" +
// " private Integer id;\n" +
// " \n" +
// " public Integer getId() {\n" +
// " return id;\n" +
// " }\n" +
// " public void setId(Integer id) {\n" +
// " this.id = id;\n" +
// " }\n" +
StrUtil.join("\n", list) +
"}\n");
return clazz;
// Object obj = clazz.newInstance();
// Method method = clazz.getDeclaredMethod("sayHello");
// method.invoke(obj);
//
// Object val = method.getDefaultValue();
// System.out.println(val);
}
// @SneakyThrows
// public static void main(String[] args) {
// HashMap<String, String> columns = new HashMap<>();
// columns.put("id", "Integer");
// columns.put("username", "String");
// columns.put("password", "String");
// columns.put("createTime", "Date");
// Class<?> mind = TableUtil.createClass("Mind",columns);
// Object o = mind.newInstance();
// String s = JSON.toJSONString(o);
// System.out.println(s);
// }
}
使用示例:
@ApiOperation("查询具体表数据-万能版")
@PostMapping("selectAllDataMagic")
@SneakyThrows
public ServiceResult selectAllDataMagic(@RequestParam @ApiParam("auto表ID") Integer autoTableId, HttpServletRequest request) {
AutoTable byId = autoTableService.getById(autoTableId);
List<AutoTableBase> autoTableBases = autoTableBaseService.lambdaQuery()
.eq(AutoTableBase::getAutoTableId, autoTableId)
.eq(AutoTableBase::getIsDeleted, 2)
.list();
HashMap<String, String> columns = new HashMap<>();
autoTableBases.forEach(autoTableBase -> {
columns.put(autoTableBase.getColumnName(), autoTableBase.getColumnType());
});
//column转成驼峰输出
Map<String, String> map = MapUtil.toCamelCaseMap(columns);
//构建运行时类。
Class<?> mind = TableUtil.createClass(byId.getTableName(), map);
return success(searcher.search(mind, MapUtils.flat(request.getParameterMap())));
}