自動代碼生成 來源 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插件基礎接口的完全限定名
      }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM