偷懒神器-->花样的代码生成工具

1、CRUD代码生成:
根据MyBatisPlus逆向工程改造而来,添加了showDoc文档生成,数据库脚本生成,增删改查文件生成,Po、Vo、Request对象生成等。普通的增删改查一般搞定。并预调了部份判断逻辑。
偷懒神器-->花样的代码生成工具_第1张图片
效果示例:

public class AddHandingPortionAdjustLogic implements ContextLogic<HandingPortionAdjustUpdateRequest> {

    @Autowired
    private HandingPortionAdjustMapper handingPortionAdjustMapper;

    @Override
    public void handleContext(HandingPortionAdjustUpdateRequest context) {
        HandingPortionAdjust handingPortionAdjust = context.getForm();
        if (null == handingPortionAdjust ) {
             throw new LocalException("调整记录参数不能为空");
        }
        handingPortionAdjustMapper.insert(handingPortionAdjust );

    }
}

2、Excel导入导出代码生成:
无他,拼字符串拼成文件,哈哈。

public class ExcelGenUtil {

    private final static Class<?> aClass = CppccMemberBackup.class;

    public static void main(String[] args) {
        String name = ZYStrUtils.firstLowerCase(aClass.getSimpleName());
        String supperName = ZYStrUtils.firstUpperCase(name);
        GenParam genParam = new GenParam();
        genParam.setAuthor("simple");
        genParam.setFileBaseDir("D:\\codeGen");
        genParam.setResponseFileName("用户");
        genParam.setExcelEntityPackageName("com.xxx.module.user.logics." + name + ".excel");
        genParam.setMapperPackageName("com.xxx.module.user.mapper." + supperName + "Mapper");
        genParam.setRequestPackageName("com.xxx.module.user.logics." + name + ".request." + supperName + "SelectRequest");
        genParam.setAClass(aClass);
        Generator.gen(genParam);
    }
}
  public static void gen(GenParam genParam) {
        ExcelExportGenerator.generateExcelModel(genParam);
        ExcelImportGenerator.generateExcelModel(genParam);
        ExcelExportModelGenerator.generateExcelModel(genParam);
        ExcelImportModelGenerator.generateExcelModel(genParam);
        System.out.println("生成完毕");
    }

偷懒神器-->花样的代码生成工具_第2张图片

3、脚本生成:
无他,拼字符串也。哈哈

    public static String INSERT_SQL = "INSERT INTO xxx (id,table_id,join_table_id,column_name,column_comment,column_type,column_places,java_name,is_show,show_width,is_query,is_querydefault,dict_type)" +
            "VALUES ('%s_%s','%s','','%s','%s','%s','column_places','%s',0,100,0,0,'%s');";

    public static void main(String[] args) {
    tableIds="xxx";
        String properties = "name";
        String propertiesName = "xx名称";
        String propertiesType = "string";
        String dictType = "";
        List<String> tableIdList = ZYListUtils.str2List(tableIds);

        List<String> sqls = new ArrayList<>();
        for (String tableId : tableIdList) {
            sqls.add(buildSql(tableId, properties, propertiesName, propertiesType, dictType));
        }
        String now = ZYDateUtils.formart(new Date(), "yyyy-MM-dd-HH-mm-ss");
        ZYFileUtils.writeLines(sqls, "D://form_coustom_sql" + now + ".sql", "UTF-8", true);
    }

    private static String buildSql(String tableId, String properties, String columnName, String type, String dictType) {
        String column = ZYStrUtils.camelToUnderline(properties);
        return String.format(INSERT_SQL, tableId, column, tableId, column, columnName, type, properties, dictType);
    }
}

4、get set this 代码生成:
无他,拼字符串尔,哈哈

public static <T> void writeSomeEasy(Class<T> clst, WriteType writeType) {
        Field[] declaredFields = clst.getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        String clasName = clst.getSimpleName();
        String newObj = clasName + " " + ZYStrUtils.firstLowerCase(clasName) + "= new " + clasName + "();";
        sb.append(newObj).append("\r\n");
        for (Field field : declaredFields) {
            String fieldName = field.getName();
            if ("serialVersionUID".equals(fieldName)) {
                continue;
            }
            String objectName = ZYStrUtils.firstLowerCase(clst.getSimpleName());
            String simpleName = field.getType().getSimpleName();
            String text = getTestByFields(writeType, fieldName, simpleName, objectName);
            sb.append(text).append("\r\n");
        }
        System.out.println(sb.toString());
    }

    private static String getTestByFields(WriteType writeType, String fieldName, String typeName, String key) {
        switch (writeType) {
            case doc_param:
                // |id|否|string|id|
                return "|" + fieldName + " |否  |" + typeName + " |" + fieldName + "   |";
            case doc_result:
                // |id|string|id|
                return "|" + fieldName + " |" + typeName + "   |" + fieldName + " |";
            case str_json_get_str:
                // String id=model.getString("id");
                return "String " + fieldName + "= " + key + ".getString(\"" + fieldName + "\");";
            case set_model:
                // model.setId(id);
                return key + ".set" + ZYStrUtils.firstUpperCase(fieldName) + "(" + fieldName + ");";
            case set_model_withmap:
                // model.setId(id);
                return key + ".set" + ZYStrUtils.firstUpperCase(fieldName) + "(importMap.getString(\"\"));";
            case get_set:
                // model.setId(model.getId());
                return key + ".set" + ZYStrUtils.firstUpperCase(fieldName) + "(" + key + ".get"
                        + ZYStrUtils.firstUpperCase(fieldName) + "());";
            case this_get_set:
                // model.setId(this.id);
                return key + ".set" + ZYStrUtils.firstUpperCase(fieldName) + "(this." + fieldName + ");";
            case this_set:
                // this.id=model.getId();
                return "this." + fieldName + "=" + key + ".get" + ZYStrUtils.firstUpperCase(fieldName) + "();";
            case type_get:
                // String id=model.getId();
                return typeName + " " + fieldName + " = " + key + "." + "get" + ZYStrUtils.firstUpperCase(fieldName)
                        + "();";
            default:
                break;
        }
        return null;
    }

    public static enum WriteType {
        doc_param, doc_result, str_json_get_str, set_model, get_set, this_get_set, this_set, type_get, set_model_withmap,
        url_param;
    }

5、ShowDoc文档生成
无他,拼字符串尔,哈哈

    public static void toJsonParam(Class<?> oneClass) throws Exception {
        Map<String, Field> fieldMap = ZYReflectUtils.getFieldMap(oneClass);
        Map<String, String> map = new HashMap<>();
        fieldMap.forEach((name, field) -> {
            final ColumnName columnName = field.getAnnotation(ColumnName.class);
            String desc = null != columnName ? columnName.value() : field.getName();
            map.put(field.getName(), desc + "#(" + field.getType().getSimpleName() + ")");
        });
        String string = JSONObject.toJSONString(map);
        System.out.println(string);
    }

    //|groupid |int   |用户组id,1:超级管理员;2:普通用户  |
    public static void toShowDocResult(Class<?> oneClass) throws Exception {
        Map<String, Field> fieldMap = ZYReflectUtils.getFieldMap(oneClass);
        fieldMap.forEach((name, field) -> {
            final ColumnName columnName = field.getAnnotation(ColumnName.class);
            String desc = null != columnName ? columnName.value() : field.getName();
            String doc = "|%s |%s|%s|";
            String format = String.format(doc, name, field.getType().getSimpleName(), desc);
            System.out.println(format);
        });
    }
}

6、项目文档需要采集数千行源代码。需要一个个文件打开复制的解决办法

public class CollectCodeDemo {

    public static void main(String[] args) {
        // 工程目录
        String dir = "D:\\javacode\\xxx\\xxx\\module-consult\\future-module-consult-service";
        // 需要的代码行数
        String outDir = "D:\\doc\\code.txt";
        projectCodeCollect(dir, 5000, outDir);


    }

    @SneakyThrows
    public static void projectCodeCollect(String dir, int line, String outDir) {
        List<String> contents = new ArrayList<>();
        projectCodeCollect(contents, new File(dir), line);
        ZYFileUtils.writeLines(contents, new File(outDir), "UTF-8", true);
    }

    private static void projectCodeCollect(List<String> contents, File dir, int line) {
        if (contents.size() >= line) {
            return;
        }
        File[] files = dir.listFiles();
        if (null == files || files.length == 0) {
            return;
        }

        for (File fileItem : files) {
            if (fileItem.isDirectory()) {
                projectCodeCollect(contents, fileItem, line);
            } else {
                String name = fileItem.getName();
                if (!name.endsWith(".java")) {
                    continue;
                }
                try (FileInputStream fileInputStream = new FileInputStream(fileItem)) {
                    List<String> lines = IOUtils.readLines(fileInputStream, "UTF-8");
                    contents.addAll(lines);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

除去MybatisPlus逆向工程需要掌屋一些velocity或freemarker的部份语法外。其他生成工具基本都是拼接字符串生成java或其他类型文档。不是很难。关键是思路问题。当一件事件具备有规律可循、大量、重复、费时、体力劳动时,就要思考会不会有更简单的办法。有的程序员早九晚五下班,有的程序员天天加班,这就是差距。人家输入几个参数生成一大堆模板文件。随便改改套套,OK搞定。有的重复着大量的体力劳动。一行一行写脚本,一个个字母写文件。仅以此文为引子。提供一种让工作更轻松,少加班的思路。

你可能感兴趣的:(java,开发语言)