从零搭建自己的SpringBoot后台框架(九)

Hello大家好,本章我们集成generator自动生成model,xml,dao功能 。有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢

ps:最近这几天在忙着搬家,更新的速度和回消息的速度可能不会特别及时,见谅

一:添加所需依赖

由于我们上篇文章讲过使用通用mapper,所以这里我们除了需要添加 mybatis-generator 之外还需要添加通用mapper提供的 generator 依赖,其次我们还需要引入两个常用jar包

<!--代码生成器-->
<dependency>
   <groupId>org.mybatis.generator</groupId>
   <artifactId>mybatis-generator-core</artifactId>
   <version>1.3.5</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>tk.mybatis</groupId>
   <artifactId>mapper-generator</artifactId>
   <version>1.0.0</version>
</dependency>

<!--常用库依赖 -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.5</version>
</dependency>
<dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>22.0</version>
</dependency>

二:创建系统日志表

CREATE TABLE `system_log` (
  `id` varchar(32) NOT NULL,
  `description` varchar(50) DEFAULT NULL COMMENT '日志信息描述',
  `method` varchar(20) DEFAULT NULL COMMENT '方法名称',
  `log_type` varchar(10) DEFAULT NULL COMMENT '日志类型 0是正常,1是异常',
  `request_ip` varchar(30) DEFAULT NULL COMMENT '请求的ip',
  `exception_code` varchar(50) DEFAULT NULL COMMENT '异常错误码',
  `exception_detail` varchar(255) DEFAULT NULL COMMENT '异常详情',
  `params` varchar(1000) DEFAULT NULL COMMENT '请求参数',
  `user_id` varchar(32) DEFAULT NULL COMMENT '请求的用户id',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='系统日志表';

三:创建系统常用变量文件夹

创建core→constant→ProjectConstant

package com.example.demo.core.constant;

public class ProjectConstant {

   // 项目基础包名称
   public static final String BASE_PACKAGE = "com.example.demo";

   // Model所在包
   public static final String MODEL_PACKAGE = BASE_PACKAGE + ".model";

   // Mapper所在包
   public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";

   // Service所在包
   public static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";

   // ServiceImpl所在包
   public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";

   // Controller所在包
   public static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".controller";

   // Mapper插件基础接口的完全限定名
   public static final String MAPPER_INTERFACE_REFERENCE = BASE_PACKAGE + ".core.universal.Mapper";

}

四:创建src/test/java/com/example/demo/CodeGenerator.java

package com.example.demo;

import com.example.demo.core.constant.ProjectConstant;
import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 代码生成器,根据数据表名称生成对应的Model、Mapper简化开发。
 * @author 张瑶
 * @date 2018/4/23 20:28
 */
public class CodeGenerator {

   // JDBC配置,请修改为你项目的实际配置
   private static final String JDBC_URL = "jdbc:mysql://localhost:3333/demo";
   private static final String JDBC_USERNAME = "root";
   private static final String JDBC_PASSWORD = "123456";
   private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
   private static final String JAVA_PATH = "src/main/java"; // java文件路径
   private static final String RESOURCES_PATH = "src/main/resources";// 资源文件路径

   /**
    * genCode("输入表名","输入自定义Model名称");
    * 如果想创建所有表,请输入"%"
    * @param args
    */
   public static void main(String[] args) {
      genCode("system_log");
   }

   /**
    * 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。 如输入表名称 "t_user_detail" 将生成
    * TUserDetail、TUserDetailMapper、TUserDetailService ...
    * 
    * @param tableNames
    *            数据表名称...
    */
   public static void genCode(String... tableNames) {
      for (String tableName : tableNames) {
         genCode(tableName, null);
      }
   }

   /**
    * 通过数据表名称,和自定义的 Model 名称生成代码 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User"
    * 将生成 User、UserMapper、UserService ...
    * 
    * @param tableName
    *            数据表名称
    * @param modelName
    *            自定义的 Model 名称
    */
   public static void genCode(String tableName, String modelName) {
      genModelAndMapper(tableName, modelName);
   }

   public static void genModelAndMapper(String tableName, String modelName) {
      Context context = getContext();

      JDBCConnectionConfiguration jdbcConnectionConfiguration = getJDBCConnectionConfiguration();
      context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

      PluginConfiguration pluginConfiguration = getPluginConfiguration();
      context.addPluginConfiguration(pluginConfiguration);

      JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = getJavaModelGeneratorConfiguration();
      context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

      SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = getSqlMapGeneratorConfiguration();
      context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

      JavaClientGeneratorConfiguration javaClientGeneratorConfiguration =getJavaClientGeneratorConfiguration();
      context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

      TableConfiguration tableConfiguration = new TableConfiguration(context);
      tableConfiguration.setTableName(tableName);
      tableConfiguration.setDomainObjectName(modelName);
      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<>();
         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 生成成功");
   }

   private static Context getContext(){
      Context context = new Context(ModelType.FLAT);
      context.setId("Potato");
      context.setTargetRuntime("MyBatis3Simple");
      context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
      context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");
      return context;
   }

   private static JDBCConnectionConfiguration getJDBCConnectionConfiguration(){
      JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
      jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
      jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
      jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
      jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
      return jdbcConnectionConfiguration;
   }

   private static PluginConfiguration getPluginConfiguration(){
      PluginConfiguration pluginConfiguration = new PluginConfiguration();
      pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
      pluginConfiguration.addProperty("mappers", ProjectConstant.MAPPER_INTERFACE_REFERENCE);
      return pluginConfiguration;
   }

   private static JavaModelGeneratorConfiguration getJavaModelGeneratorConfiguration(){
      JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
      javaModelGeneratorConfiguration.setTargetProject(JAVA_PATH);
      javaModelGeneratorConfiguration.setTargetPackage(ProjectConstant.MODEL_PACKAGE);
      javaModelGeneratorConfiguration.addProperty("enableSubPackages","true");
      javaModelGeneratorConfiguration.addProperty("trimStrings","true");
      return javaModelGeneratorConfiguration;
   }

   private static SqlMapGeneratorConfiguration getSqlMapGeneratorConfiguration(){
      SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
      sqlMapGeneratorConfiguration.setTargetProject(RESOURCES_PATH);
      sqlMapGeneratorConfiguration.setTargetPackage("mapper");
      return sqlMapGeneratorConfiguration;
   }

   private static JavaClientGeneratorConfiguration getJavaClientGeneratorConfiguration(){
      JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
      javaClientGeneratorConfiguration.setTargetProject(JAVA_PATH);
      javaClientGeneratorConfiguration.setTargetPackage(ProjectConstant.MAPPER_PACKAGE);
      javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
      return javaClientGeneratorConfiguration;
   }

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

五:功能测试

CodeGenerator 中右键run

从零搭建自己的SpringBoot后台框架(九)

从零搭建自己的SpringBoot后台框架(九)

ok,创建成功

项目地址

gitee.com/beany/mySpr…

写文章不易,如对您有帮助,请帮忙点下star 从零搭建自己的SpringBoot后台框架(九)

结尾

集成generator自动生成model,xml,dao功能已完成,后续功能接下来陆续更新,有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢大家。

原文 

https://juejin.im/post/5adff22f6fb9a07ac76e79a3

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 从零搭建自己的SpringBoot后台框架(九)

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址