Mybatis 代码生成插件

首先是所需要的依赖文件

    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>1.2.4</version>
    </dependency>

    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.4</version>
    </dependency>

    <!-- mybatis代码生成工具-->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>16.0</version>
    </dependency>
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.23</version>
    </dependency>
复制代码

其次是CodeGenerator这个文件,可以生成Service、ServiceImpl、model、mapper、dao这些文件以及文件夹,和这个文件对应的还有模版文件在template文件夹中

    package com.example.project;
    
    import com.google.common.base.CaseFormat;
    import freemarker.template.TemplateExceptionHandler;
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.*;
    import org.mybatis.generator.internal.DefaultShellCallback;
    import org.springframework.util.StringUtils;
    import tk.mybatis.mapper.util.StringUtil;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    
    /**
     * 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。
     */
    public class CodeGenerator {
        /**
         * JDBC配置
         */
        private static final String JDBC_URL = "jdbc:mysql://127.0.0.1:3306/Test";
        private static final String JDBC_USERNAME = "root";
        private static final String JDBC_PASSWORD = "12345678";
        private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
    
        /**
         * 项目路径相关
         */
        private static final String PROJECT_PATH = "/Users/Macx/github/springboot-mybaits-redis"; // 项目基础路径
        private static final String TEMPLATE_PATH = "/Users/Macx/github/springboot-mybaits-redis/src/main/resources/template"; // 代码模板路径
        public static final String BASE_PACKAGE = "com.example.project";//项目基础包名称,根据自己公司的项目修改
        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 + ".controller";//Controller所在包
        public static final String MAPPER_INTERFACE_REFERENCE = "com.example.project.mybatis.MyMapper";//Mapper插件基础接口的完全限定名
    
        private static final String PACKAGE_PATH_SERVICE = packageConvertPath(SERVICE_PACKAGE);//生成的Service存放路径
        private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
        private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(CONTROLLER_PACKAGE);//生成的Controller存放路径
    
        private static final String AUTHOR = "wenqing";//@author
        private static final String DATE = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());//@date
        //java文件路径
        private static final String JAVA_PATH = "/src/main/java";
        //资源文件路径
        private static final String RESOURCES_PATH = "/src/main/resources";
    
        /**
         * 运行main方法
         *
         * @param args
         */
        public static void main(String[] args) {
            genCodeByCustomModelName("tbl_product", "Product");
        }
    
    
        /**
         * 通过数据表名称,和自定义的 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);
        }
    
        /**
         * 生成model&&mapper
         *
         * @param tableName
         * @param modelName
         */
        public static void genModelAndMapper(String tableName, String modelName) {
            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);
    
            PluginConfiguration pluginConfiguration = new PluginConfiguration();
            pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
            pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE);
            context.addPluginConfiguration(pluginConfiguration);
    
            JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
            javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
            javaModelGeneratorConfiguration.setTargetPackage(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(MAPPER_PACKAGE);
            javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
            context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
    
            TableConfiguration tableConfiguration = new TableConfiguration(context);
            tableConfiguration.setTableName(tableName);
            if (StringUtil.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<>();
                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 生成成功");
        }
    
        /**
         * 生成service
         *
         * @param tableName
         * @param modelName
         */
        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", BASE_PACKAGE);
    
                File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + "I" + 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);
            }
        }
    
        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_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) {
            return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
    
        }
    
        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);
        }
    }
复制代码

对应的模版文件 service.ftl和service-impl.ftl

    package ${basePackage}.service;
    import ${basePackage}.model.${modelNameUpperCamel};
    import com.example.project.mybatis.Service;
    
    /**
    * @author: ${author}
    * @date: ${date}
    * @description: ${modelNameUpperCamel}服务接口
    */
    public interface I${modelNameUpperCamel}Service extends Service<${modelNameUpperCamel}> {
    
    }
    
    
    

package ${basePackage}.service.impl;

import ${basePackage}.dao.${modelNameUpperCamel}Mapper;
import ${basePackage}.model.${modelNameUpperCamel};
import ${basePackage}.service.I${modelNameUpperCamel}Service;
import com.example.project.mybatis.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;


/**
* @author: ${author}
* @date: ${date}
* @description: ${modelNameUpperCamel}服务实现
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ${modelNameUpperCamel}ServiceImpl extends AbstractService<${modelNameUpperCamel}> implements I${modelNameUpperCamel}Service {

    @Autowired
    private ${modelNameUpperCamel}Mapper ${modelNameLowerCamel}Mapper;

}
复制代码

转载于:https://juejin.im/post/5cec01ea51882559685b3638

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值