mybatis-generator

MyBatis Generator官方文档

MyBatis Generator官方文档(Plugin)

插件可用于修改或添加由MyBatis Generator生成的对象。插件必须实现org.mybatis.generator.api.Plugin接口 。插件接口包含许多在代码生成过程的不同阶段调用的方法。任何特定插件通常都不需要实现整个界面。因此,大多数插件应该扩展适配器类org.mybatis.generator.api.PluginAdapter。适配器类提供基本的插件支持,并为大多数接口方法实现无操作方法(类似于Swing适配器类)。
<plugin type="com.dolphin.mybatis.generator.BasePlugin" />

实现插件的最佳方法是扩展 org.mybatis.generator.api.PluginAdapter类,并仅覆盖插件中所需的特定方法。

public class BasePlugin extends PluginAdapter {
}

如果我们要在实体类上增加自定义注释和注解 只需要重写modelBaseRecordClassGenerated方法

package com.dolphin.mybatis.generator;

import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.IntrospectedTable;

public class BasePlugin extends PluginAdapter {
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        // 增加注释
        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine("* 开发公司:青岛海豚数据技术有限公司");
        topLevelClass.addJavaDocLine("* 版权:青岛海豚数据技术有限公司");
        topLevelClass.addJavaDocLine("* Class");
        topLevelClass.addJavaDocLine("* " + topLevelClass.getType().getShortName());
        topLevelClass.addJavaDocLine("*");
        topLevelClass.addJavaDocLine("* @author 系统");
        topLevelClass.addJavaDocLine("* @created Create Time: " + new Date());
        topLevelClass.addJavaDocLine("*/");
        // 导入注解对应的开发包
        Set<FullyQualifiedJavaType> set = new HashSet<FullyQualifiedJavaType>();
        set.add(new FullyQualifiedJavaType("io.swagger.annotations.ApiModel"));
        set.add(new FullyQualifiedJavaType("lombok.Data"));
        topLevelClass.addImportedTypes(set); //导入注解对应的开发包
        // 增加注解
        topLevelClass.addAnnotation("@ApiModel" + "(value=\"" + topLevelClass.getType() + "\",description=\"" + introspectedTable.getRemarks() + "\")");
        topLevelClass.addAnnotation("@Data");
    }
}

对应的修改

clientGenerated //生成mapper接口调用的方法
modelFieldGenerated //生成实体类每个字段调用的方法
modelSetterMethodGenerated //生成实体类字段set方法调用的方法
modelGetterMethodGenerated //生成实体类字段get方法调用的方法
clientxxxxxxxMethodGenerated //生成对应mapper接口内方法调用的方法
sqlMapXXXElementGenerated(XmlElement,IntrospectedTable)在生成SQL映射的每个元素时调用这些方法
sqlMapDocumentGenerated(Document,IntrospectedTable)
sqlMapDocument(GeneratedXmlFile,IntrospectedTable)

对于额外Controller等额外文件,我们可以借助FreeMarker模板在指定位置创建文件,如Controller.ftl

package ${package_controller};

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ${package_service}.${file_name}Service;
import com.dolphin.common.tool.BaseController;

/**
 * 开发公司:青岛海豚数据技术有限公司
 * 版权:青岛海豚数据技术有限公司
 * <p>
 *  ${file_name}Controller
 *
 * @author 系统
 * @created Create Time: ${date?string('yyyy-MM-dd hh:mm:ss')}
*/
@RestController
@RequestMapping("/${module_name}")
@CrossOrigin
@Api(description = "相关的api")
public class ${file_name}Controller extends BaseController {

    @Autowired
    public ${file_name}Service ${file_name?uncap_first}Service;

}

将Controller.ftl里表达式的值替换掉就是一个初始的Controller.java文件了

新建FreeMarker模板工具类

package com.dolphin.mybatis.generator;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;

/**
 * 开发公司:青岛海豚数据技术有限公司
 * 版权:青岛海豚数据技术有限公司
 * <p>
 * FreeMarkerTemplateUtils
 *
 * @author 刘志强
 * @created Create Time: 2019/1/22
 */
public class FreeMarkerTemplateUtils {
    private FreeMarkerTemplateUtils(){}
    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

    static{
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/generator/template"));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    public static Template getTemplate(String templateName) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }

    public static void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }
}

修改plugin标签,追加property标签填写文件路径。如下

<plugin type="com.dolphin.mybatis.generator.BasePlugin">
     <property name="controller" value="com.dolphin.sigle.root.controller.sys"/>
     <property name="service" value="com.dolphin.sigle.root.service.sys"/>
</plugin>

修改modelBaseRecordClassGenerated方法

public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
    // 取出controller的value值
    String packageController = properties.getProperty("controller");
    if (packageController != null) {
        String packageService = properties.getProperty("service");

        String[] mulu = properties.getProperty("controller").split("\\.");
        String moduleName = mulu[mulu.length - 1];
        String fileName = topLevelClass.getType().getShortName();

        String path = introspectedTable.getContext().getJavaModelGeneratorConfiguration().getTargetProject() + "/" + properties.getProperty("controller").replaceAll("\\.", "/");
        File catalog = new File(path);
        catalog.mkdirs();
        File mapperFile = new File(path + '/' + fileName + "Controller.java");
        Template template = FreeMarkerTemplateUtils.getTemplate("Controller.ftl");
        FileOutputStream fos = new FileOutputStream(mapperFile);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
        
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("package_controller", packageController);
        dataMap.put("package_service", packageService);
        dataMap.put("module_name", moduleName);
        dataMap.put("file_name", fileName);
        dataMap.put("date", new Date());

        template.process(dataMap, out);
    }
}

MBG启动方式Java启动或者maven启动

Java启动
public class GenerateStartUp {

    public static void main(String[] args) {
        List<String> warnings = new ArrayList<String>();
        try {
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("mybatis-generator.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}
maven启动 pom 文件增加plugin
<build>
        <plugins>
            <!--mybatis-generator数据表自动生成-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.21</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                    <dependency>
                        <groupId>com.liuzhiqiang.tools</groupId>
                        <artifactId>generator-extend</artifactId>
                        <version>2.1-SNAPSHOT</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <!--允许移动生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆盖 -->
                    <overwrite>true</overwrite>
                    <!-- 自动生成的配置 -->
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml
                    </configurationFile>
                </configuration>
            </plugin>

        </plugins>
    </build>

github地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值