Java运行时构建实体类-工具类


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())));
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值