自动代码生成 来源 GitHub上的项目

自动代码生成

在开发的过程中,我们老是重复的去搭建一个一些类,这次笔记是从GitHub上整理的,就是生成那些mvc 的基础类实现,让我们花更多的时间在业务上的实现,
https://github.com/lihengming/spring-boot-api-project-seed
  • 主要包引入

      <dependency>
          <groupId>org.freemarker</groupId>
          <artifactId>freemarker</artifactId>
          <version>2.3.23</version>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.5</version>
          <scope>test</scope>
      </dependency>
  • 基本流程思路:

    设置一个类:这个类具有数据库连接的基本信息

    设置一个枚举:主要的存放我们项目的构造路径 mvc 那些包的路径

    创建代码的模板:这个根据自己的想放在就放在那决定

  •       public class CodeGenerator {
          private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:orcl";
               private static final String JDBC_USERNAME = "system";
               private static final String JDBC_PASSWORD = "123456";
               private static final String JDBC_DIVER_CLASS_NAME = "oracle.jdbc.driver.OracleDriver";
    
               private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
               private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/test/resources/generator/template";//模板位置
    
               private static final String JAVA_PATH = "/src/main/java"; //java文件路径
               private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径
               private static final String PACKAGE_PATH_SERVICE = packageConvertPath(ProjectConstant.SERVICE_PACKAGE);//生成的Service存放路径
               private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(ProjectConstant.SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
               private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(ProjectConstant.CONTROLLER_PACKAGE);//生成的Controller存放路径
    
               private static final String AUTHOR = "CodeGenerator";//@author
               private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date
    
               public static void main(String[] args) {
                         genCode("jx_user");
                         //genCodeByCustomModelName("输入表名","输入自定义Model名称");
               }
               private static String packageConvertPath(String packageName) {
                       return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\.", "/") : packageName);
               }
                /**
                    * 通过数据表名称,和自定义的 Model 名称生成代码
                    * 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
                    * @param tableName 数据表名称
                    * @param modelName 自定义的 Model 名称
                    */
                   public static void genCodeByCustomModelName(String tableName, String modelName) {
                       genModelAndMapper(tableName, modelName);
                       genService(tableName, modelName);
                       genController(tableName, modelName);
                   }
                 public static void genModelAndMapper(String tableName, String modelName) {
                     //配置mybatis 的环境
                     Context context = new Context(ModelType.FLAT);
                     context.setId("Potato");
                     context.setTargetRuntime("MyBatis3Simple");
                     context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
                     context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");

                     //配置数据库连接属性
                     JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
                     jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
                     jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
                     jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
                     jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
                     context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

                     //配置插件,这个插件是用来生成mapper文件的
                     PluginConfiguration pluginConfiguration = new PluginConfiguration();
                     pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
                     pluginConfiguration.addProperty("mappers", ProjectConstant.MAPPER_INTERFACE_REFERENCE);
                     context.addPluginConfiguration(pluginConfiguration);

                     //设置生成model 实体类的路径
                     JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
                     javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
                     javaModelGeneratorConfiguration.setTargetPackage(ProjectConstant.MODEL_PACKAGE);
                     context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

                     SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
                     sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
                     sqlMapGeneratorConfiguration.setTargetPackage("mapper");
                     context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

                     JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
                     javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
                     javaClientGeneratorConfiguration.setTargetPackage(ProjectConstant.MAPPER_PACKAGE);
                     javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
                     context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

                     TableConfiguration tableConfiguration = new TableConfiguration(context);
                     tableConfiguration.setTableName(tableName);
                     if (StringUtils.isNotEmpty(modelName))tableConfiguration.setDomainObjectName(modelName);
                     tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
                     context.addTableConfiguration(tableConfiguration);

                     List<String> warnings;
                     MyBatisGenerator generator;
                     try {
                         Configuration config = new Configuration();
                         config.addContext(context);
                         config.validate();

                         boolean overwrite = true;
                         DefaultShellCallback callback = new DefaultShellCallback(overwrite);
                         warnings = new ArrayList<String>();
                         generator = new MyBatisGenerator(config, callback, warnings);
                         generator.generate(null);
                     } catch (Exception e) {
                         throw new RuntimeException("生成Model和Mapper失败", e);
                     }

                     if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
                         throw new RuntimeException("生成Model和Mapper失败:" + warnings);
                     }
                     if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName);
                     System.out.println(modelName + ".java 生成成功");
                     System.out.println(modelName + "Mapper.java 生成成功");
                     System.out.println(modelName + "Mapper.xml 生成成功");
                 }

                 public static void genService(String tableName, String modelName) {
                     try {
                         freemarker.template.Configuration cfg = getConfiguration();

                         Map<String, Object> data = new HashMap<>();
                         data.put("date", DATE);
                         data.put("author", AUTHOR);
                         String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
                         data.put("modelNameUpperCamel", modelNameUpperCamel);
                         data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName));
                         data.put("basePackage", ProjectConstant.BASE_PACKAGE);

                         File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
                         if (!file.getParentFile().exists()) {
                             file.getParentFile().mkdirs();
                         }
                         cfg.getTemplate("service.ftl").process(data,
                                 new FileWriter(file));
                         System.out.println(modelNameUpperCamel + "Service.java 生成成功");

                         File file1 = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
                         if (!file1.getParentFile().exists()) {
                             file1.getParentFile().mkdirs();
                         }
                         cfg.getTemplate("service-impl.ftl").process(data,
                                 new FileWriter(file1));
                         System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功");
                     } catch (Exception e) {
                         throw new RuntimeException("生成Service失败", e);
                     }
                 }

                 public static void genController(String tableName, String modelName) {
                     try {
                         freemarker.template.Configuration cfg = getConfiguration();

                         Map<String, Object> data = new HashMap<>();
                         data.put("date", DATE);
                         data.put("author", AUTHOR);
                         String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
                         data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
                         data.put("modelNameUpperCamel", modelNameUpperCamel);
                         data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
                         data.put("basePackage", ProjectConstant.BASE_PACKAGE);

                         File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
                         if (!file.getParentFile().exists()) {
                             file.getParentFile().mkdirs();
                         }
                         //cfg.getTemplate("controller-restful.ftl").process(data, new FileWriter(file));
                         cfg.getTemplate("controller.ftl").process(data, new FileWriter(file));

                         System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
                     } catch (Exception e) {
                         throw new RuntimeException("生成Controller失败", e);
                     }

                 }

                 private static freemarker.template.Configuration getConfiguration() throws IOException {
                     freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
                     cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
                     cfg.setDefaultEncoding("UTF-8");
                     cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                     return cfg;
                 }

                 private static String tableNameConvertLowerCamel(String tableName) {
                     return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase());
                 }

                 private static String tableNameConvertUpperCamel(String tableName) {
                     try {
                         return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
                     }catch (Exception e){
                         e.printStackTrace();
                         return e.getMessage();
                     }
                 }

                 private static String tableNameConvertMappingPath(String tableName) {
                     tableName = tableName.toLowerCase();//兼容使用大写的表名
                     return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName);
                 }

                 private static String modelNameConvertMappingPath(String modelName) {
                     String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
                     return tableNameConvertMappingPath(tableName);
                 }

                 private static String packageConvertPath(String packageName) {
                     return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\.", "/") : packageName);
                 }

       } 
   >tk.mybatis.mapper.generator.MapperPlugin 这个插件这里记录没有,该整理的内容来自github上[spring boot+mybatis](https://github.com/lihengming/spring-boot-api-project-seed)
  • 枚举

      /**
       * 项目常量
       */
      public final class ProjectConstant {
          public static final String BASE_PACKAGE = "com.company.project";//生成代码所在的基础包名称,可根据自己公司的项目修改(注意:这个配置修改之后需要手工修改src目录项目默认的包路径,使其保持一致,不然会找不到类)
    
          public static final String MODEL_PACKAGE = BASE_PACKAGE + ".model";//生成的Model所在包
          public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";//生成的Mapper所在包
          public static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";//生成的Service所在包
          public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";//生成的ServiceImpl所在包
          public static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".web";//生成的Controller所在包
    
          public static final String MAPPER_INTERFACE_REFERENCE = BASE_PACKAGE + ".core.Mapper";//Mapper插件基础接口的完全限定名
      }
原文地址:https://www.cnblogs.com/youer66/p/10196330.html