In this chapter, we integrate generator to automatically generate Model, XML and DAO. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you

Ps: I have been busy moving in recent days, so the speed of update and reply may not be particularly timely, sorry for that

One: Add required dependencies

In addition to mybatis -Generator, we also need to add the generator dependencies provided by the universal Mapper. In addition, we also need to introduce two common JAR packages

<! 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> The < version > 1.0.0 < / version > < / dependency > <! Commons -lang3</artifactId> Commons -lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>com.google.guava</ artifactId> The < version > 22.0 < / version > < / dependency >Copy the code

Two: Create a system log table

CREATE TABLE `system_log` (
  `id` varchar(32) NOT NULL,
  `description` varchar(50) DEFAULT NULL COMMENT 'Log Information Description',
  `method` varchar(20) DEFAULT NULL COMMENT 'Method name',
  `log_type` varchar(10) DEFAULT NULL COMMENT 'Log type 0 is normal, log type 1 is abnormal',
  `request_ip` varchar(30) DEFAULT NULL COMMENT 'Requested IP',
  `exception_code` varchar(50) DEFAULT NULL COMMENT 'Exception error code',
  `exception_detail` varchar(255) DEFAULT NULL COMMENT 'Exception Details',
  `params` varchar(1000) DEFAULT NULL COMMENT 'Request Parameters',
  `user_id` varchar(32) DEFAULT NULL COMMENT 'Requested user ID',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='System Log Table';Copy the code

Create folders of common variables in the system

To create the core – constant – ProjectConstant

package com.example.demo.core.constant; Public class ProjectConstant {// Project base package name public static final String BASE_PACKAGE ="com.example.demo"; Public static final String MODEL_PACKAGE = BASE_PACKAGE +".model"; Mapper package public static final String MAPPER_PACKAGE = BASE_PACKAGE +".dao"; Public static final String SERVICE_PACKAGE = BASE_PACKAGE +".service"; Public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE +".impl"; Public static final String CONTROLLER_PACKAGE = BASE_PACKAGE +".controller"; // Fully qualified name of the base interface of the Mapper plug-in public static final String MAPPER_INTERFACE_REFERENCE = BASE_PACKAGE +".core.universal.Mapper";

}Copy the code

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: code generator, according to the name of the data table to generate the corresponding Model, Mapper to simplify development. */ public class CodeGenerator {// JDBC configuration, Please change to the actual configuration of your project 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 file path private static final String RESOURCES_PATH ="src/main/resources"; /** * genCode()"Enter table name"."Enter a custom Model name"); * Enter if you want to create all tables"%"
    * @param args
    */
   public static void main(String[] args) {
      genCode("system_log"); } /** * Generate code from the table name, the Model name is obtained by parsing the table name, underline to large hump form. For example, enter a table name"t_user_detail"Will generate * TUserDetail, TUserDetailMapper, TUserDetailService... * * @param tableNames * table name... */ public static void genCode(String... tableNames) {for(String tableName : tableNames) { genCode(tableName, null); }} /** * Generate code from table names and custom Model names such as input table names"t_user_detail"And custom Model names"User"* Will generate User, UserMapper, UserService... * * @param tableName * @param modelName */ 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("Failed to generate Model and Mapper", e);
      }

      if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
         throw new RuntimeException(Failed to generate Model and Mapper: + warnings);
      }
      if (StringUtils.isEmpty(modelName)){
         modelName = tableNameConvertUpperCamel(tableName);
      }
      System.out.println(modelName + ".java generated successfully");
      System.out.println(modelName + Mapper. Java generated successfully);
      System.out.println(modelName + Mapper. XML generated successfully);
   }

   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) {
      returnCaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase()); }}Copy the code

Five: functional testing

Right-click Run in CodeGenerator





Ok, the creation is successful

The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

The functions of integrating generator to automatically generate model, XML and DAO have been completed, and the subsequent functions will be updated successively. If you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.