mybatis generator插件编写

文章目录


MyBatis Generator Plugin
Plugin用来在生成Java及XML的过程中修改或者添加内容。

其必须实现com.mybatis.generator.api.Plugin接口。大多数插件应扩展适配器类org.mybatis.generator.api.PluginAdapter 。适配器类提供基本的插件支持,并为大多数的接口方法(类似于Swing适配器类)提供了空操作的方法。

插件的生命周期
插件通过默认的构造函数创建
setContext方法被调用
setProperties方法被调用
validate方法被调用。如果该方法返回false ,那么插件中的其他方法都不会再被调用。
对于配置中的每个表:
initialized方法被调用
Java客户端的方法:
clientXXXMethodGenerated(Method, TopLevelClass, IntrospectedTable) - 当Java客户端实现类生成的时候这些方法被调用.
clientXXXMethodGenerated(Method, Interface, IntrospectedTable) -当Java客户端接口生成的时候这些方法被调用。
clientGenerated(Interface, TopLevelClass, IntrospectedTable)方法被调用
模型方法:
modelFieldGenerated, modelGetterMethodGenerated, modelSetterMethodGenerated for each field in the class
modelExampleClassGenerated(TopLevelClass, IntrospectedTable)
modelPrimaryKeyClassGenerated(TopLevelClass, IntrospectedTable)
modelBaseRecordClassGenerated(TopLevelClass, IntrospectedTable)
modelRecordWithBLOBsClassGenerated(TopLevelClass, IntrospectedTable)
SQL映射方法:
sqlMapXXXElementGenerated(XmlElement, IntrospectedTable) - 当生成SQL映射的每个元素的时候这些方法被调用
sqlMapDocumentGenerated(Document, IntrospectedTable)
sqlMapDocument(GeneratedXmlFile, IntrospectedTable)
contextGenerateAdditionalJavaFiles(IntrospectedTable)方法被调用
contextGenerateAdditionalXmlFiles(IntrospectedTable)方法被调用
contextGenerateAdditionalJavaFiles()方法被调用
contextGenerateAdditionalXmlFiles()方法被调用
可以在以下方法中生成自定义的xml或者Java文件:

contextGenerateAdditionalJavaFiles(IntrospectedTable)
contextGenerateAdditionalXmlFiles(IntrospectedTable)
contextGenerateAdditionalJavaFiles()
contextGenerateAdditionalXmlFiles()
如果生成的xml或者Java文件和当前的配置中的表相关,如需要根据每个表的xml及client生成新的自定义的xml或client,则使用带有参数的:

contextGenerateAdditionalJavaFiles(IntrospectedTable)
contextGenerateAdditionalXmlFiles(IntrospectedTable)
否则可以使用不带参数的:

contextGenerateAdditionalJavaFiles()
contextGenerateAdditionalXmlFiles()
如我们需要生成mybatis-config.xml配置文件,该文件和具体的表无关,则可以使用contextGenerateAdditionalXmlFiles().
可以参考muybatis-generator-core包里面plugin目录下的SqlMapConfigPlugin。

生成自定义Mapper及xml
如果我们把自己的业务写在默认的Mapper.java及Mapper.xml中时,如果业务很多,会发现代码很乱,如果想和默认的进行区分,
并且方便重新生成,则编写插件进行生成。

目的:

支持对生成的Mapper进行重命名,如需要把默认的Mapper生成为Dao
支持把默认的Mapper.java生成在mbg目录下,Mapper.xml生成在相应的mbg目录下
支持在custom目录生成新的Mappper.java及xml
其生成结构如:

src
├── main
│ ├── java
│ │ └── com
│ │ ├── demo
│ │ │ └── monitor
│ │ │ └── aly
│ │ │ ├── App.java
│ │ │ ├── config
│ │ │ │ └── AppConfig.java
│ │ │ ├── controller
│ │ │ │ └── IndexController.java
│ │ │ ├── dao
│ │ │ │ ├── custom
│ │ │ │ │ ├── EcsInfoMapper.java
│ │ │ │ │ └── SlbInfoMapper.java
│ │ │ │ └── mbg
│ │ │ │ ├── EcsInfoMBGMapper.java
│ │ │ │ └── SlbInfoMBGMapper.java
│ │ │ ├── model
│ │ │ │ ├── EcsInfo.java
│ │ │ │ └── SlbInfo.java
│ │ │ └── service
│ │ │ └── EcsInfoService.java
│ │ └── kkk
│ └── resources
│ ├── application.yml
│ ├── generatorConfig.xml
│ ├── log4j2.xml
│ ├── mapper
│ │ ├── custom
│ │ │ ├── EcsInfoMapper.xml
│ │ │ └── SlbInfoMapper.xml
│ │ └── mbg
│ │ ├── EcsInfoMBGMapper.xml
│ │ └── SlbInfoMBGMapper.xml
│ └── mybatis-config.xml
└── test
└── java
其代码如下:

import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.XmlConstants;
import org.mybatis.generator.internal.util.StringUtility;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RenamePlugin extends PluginAdapter {
private String searchStr;
private String replaceStr;
private Pattern pattern;
private boolean replaceFlag;

@Override
public boolean validate(List<String> list) {
    searchStr = properties.getProperty("searchString");
    replaceStr = properties.getProperty("replaceString");
    boolean valid = StringUtility.stringHasValue(searchStr) && StringUtility.stringHasValue(replaceStr);

    if (valid) {
        pattern = Pattern.compile(searchStr);
        replaceFlag = true;
    } else {
        searchStr = "";
        replaceStr = "";
    }

    return true;
}

/**
* 重命名及更改默认的目录
* @param introspectedTable
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
    //更改默认生成的Mapper.java为mbg目录下MBGMapper.java
    String oldType = introspectedTable.getMyBatis3JavaMapperType();
    if (replaceFlag) {
        Matcher matcher = pattern.matcher(oldType);
        oldType = matcher.replaceAll("MBG" + replaceStr);
    } else {
        oldType = oldType.replaceAll("Mapper", "MBGMapper");
    }
    int idx = oldType.lastIndexOf(".");
    if (idx > 0) {
        oldType = oldType.substring(0, idx) + ".mbg" + oldType.substring(idx);
    }
    introspectedTable.setMyBatis3JavaMapperType(oldType);
    //更改默认生成的Mapper.java为mbg目录下MBGMapper.java
    String mapperName = introspectedTable.getMyBatis3XmlMapperFileName();
    if (replaceFlag) {
        Matcher matcher = pattern.matcher(oldType);
        mapperName = matcher.replaceAll("MBG" + replaceStr);
    } else {
        mapperName = mapperName.replaceAll("Mapper", "MBGMapper");
    }
    introspectedTable.setMyBatis3XmlMapperFileName(mapperName);
    String mapperPkg = introspectedTable.getMyBatis3XmlMapperPackage() + File.separator + "mbg";
    introspectedTable.setMyBatis3XmlMapperPackage(mapperPkg);
}

@Override
public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
    List<GeneratedJavaFile> result = new ArrayList<>();
    GeneratedJavaFile g = null;
    for (GeneratedJavaFile f : introspectedTable.getGeneratedJavaFiles()) {
        if (f.getFileName().contains("Dao") || f.getFileName().contains("Mapper")) {
            g = f;
            break;
        }
    }
    if (g != null) {
        String pkgName = g.getTargetPackage().replace("mbg", "custom");
        String className = g.getCompilationUnit().getType().getShortName().replace("MBG", "");
        Interface customInterface = new Interface(pkgName + "." + className);
        customInterface.setVisibility(JavaVisibility.PUBLIC);

        FullyQualifiedJavaType daoType = new FullyQualifiedJavaType(g.getCompilationUnit().getType().getFullyQualifiedName());
        customInterface.addSuperInterface(daoType);
        customInterface.addImportedType(daoType);
        String target = g.getTargetProject();
        String fileName = (target + File.separator + pkgName + "." + className).replace(".", File.separator);
        File file = new File(fileName + ".java");
        if (!file.exists()) {
            GeneratedJavaFile tmp = new GeneratedJavaFile(customInterface, target, context.getJavaFormatter());
            result.add(tmp);
        }
    }
    return result;
}

/**
* 为相应的默认的xml文件生成一个自定义的xml,自己实现的可以都写在该文件中
* @param introspectedTable
* @return
*/
@Override
public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles(IntrospectedTable introspectedTable) {
    List<GeneratedXmlFile> result = new ArrayList<>();
    GeneratedXmlFile mbgXml = introspectedTable.getGeneratedXmlFiles().get(0);
    String projectName = mbgXml.getTargetProject();
    String packageName = mbgXml.getTargetPackage().replace("mbg", "custom");
    GeneratedJavaFile g = null;
    for (GeneratedJavaFile f : introspectedTable.getGeneratedJavaFiles()) {
        if (f.getFileName().contains("Dao") || f.getFileName().contains("Mapper")) {
            g = f;
            break;
        }
    }
    if (g != null) {
        Document document = new Document(XmlConstants.MYBATIS3_MAPPER_CONFIG_PUBLIC_ID,
                XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID);
        XmlElement root = new XmlElement("mapper");
        String className = g.getFileName().replace("MBG", "");
        String fileName = g.getFileName().replace("MBG", "").replace(".java", ".xml");
        String pkgName = g.getTargetPackage().replace(".mbg", ".custom");
        Attribute attribute = new Attribute("namespace", pkgName + "." + className.replace(".java", ""));
        root.addAttribute(attribute);
        document.setRootElement(root);

        File file = new File(projectName + File.separator + packageName + File.separator + fileName);
        if (!file.exists()) {
            GeneratedXmlFile gxf = new GeneratedXmlFile(document, fileName, packageName,
                    projectName, false, context.getXmlFormatter());
            result.add(gxf);
        }
    }
    return result;
}

}
自定义插件
功能:美化model的生成样式,其中属性注释为:列名 : 列注释

package com.liukun.mgenerator;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

/**

  • Created by HFJY on 2017/6/30.
    */
    public class Demo extends PluginAdapter {
    private void print(Throwable throwable) {
    System.out.println(throwable.getStackTrace()[0].getMethodName());
    }

    @Override
    public boolean validate(List list) {
    return true;
    }

    @Override
    public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
    method.getJavaDocLines().set(1," * clientDeleteByPrimaryKeyMethodGenerated!测试");
    method.getJavaDocLines().remove(2);
    return super.clientDeleteByPrimaryKeyMethodGenerated(method, interfaze, introspectedTable);
    }

    @Override
    public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
    field.getJavaDocLines().set(1," * " + introspectedColumn.getActualColumnName() + " : " + introspectedColumn.getRemarks());
    field.getJavaDocLines().remove(2);
    field.getJavaDocLines().remove(2);
    return super.modelFieldGenerated(field, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
    }

    @Override
    public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
    method.getJavaDocLines().remove(1);
    method.getJavaDocLines().remove(1);
    return super.modelGetterMethodGenerated(method, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
    }

    @Override
    public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
    method.getJavaDocLines().remove(1);
    method.getJavaDocLines().remove(1);
    return super.modelSetterMethodGenerated(method, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
    }
    }
    项目进行打包,其它项目在maven中引用该插件

org.mybatis.generator mybatis-generator-maven-plugin 1.3.5 true org.mybatis.generator mybatis-generator-core 1.3.5 mysql mysql-connector-java 5.1.38 com.liukun.mybatis.generator demogenerator 1.0-SNAPSHOT 并且在resources/generatorConfig.xml中相应的context下引入该插件即可:


这时就可以通过mvn mybatis-generator:generate进行插件的生成

0人点赞
Java作者:三无架构师链接:https://www.jianshu.com/p/5117d51d49e1来源:简书

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: MyBatis Generator插件是一个自动生成MyBatis代码的工具,它可以根据数据库表结构自动生成对应的Java实体类、Mapper接口和XML映射文件。使用该插件可以大大提高开发效率,减少手写代码的工作量。同时,该插件还支持自定义生成规则和插件扩展,可以满足不同项目的需求。 ### 回答2: MyBatis Generator插件是一个用于生成MyBatis持久层代码的工具。它通过读取数据库表结构信息,自动生成对应的实体类、Mapper接口以及XML映射文件。 该插件的核心功能是根据数据库表结构生成对应的实体类。它会根据表的字段类型和命名规则,自动创建实体类的属性和对应的getter和setter方法。这样可以大大简化实体类的编写工作,提高开发效率。 除了实体类,插件还会生成Mapper接口和XML映射文件。Mapper接口定义了数据库操作的方法,而XML映射文件提供了数据库操作的具体实现。这样,在使用MyBatis时,我们只需要编写Mapper接口的方法,而不需要手动编写SQL语句,MyBatis Generator会帮助我们自动生成。 插件还提供了一些配置选项,可以根据需要进行个性化设置。我们可以指定生成的代码的包名、文件保存路径等信息。另外,插件还支持自定义模板,可以根据需求修改生成代码的样式。 总之,MyBatis Generator插件是一个非常实用的工具,可以大大简化MyBatis代码的编写工作。它通过自动生成实体类、Mapper接口和XML映射文件,提高了开发效率,减少了出错的可能性。它的灵活配置和自定义模板功能,还可以满足开发者个性化的需求。 ### 回答3: MyBatis Generator是一个开源的代码生成工具,它可以根据数据库表结构自动生成对应的Java模型对象、Mapper接口和XML映射文件。 MyBatis Generator使用了类似于MyBatis的SQL映射语言来生成代码,用户只需编写一个名为"generatorConfig.xml"的配置文件,指定数据库连接信息、要生成代码的表信息以及代码生成的目标路径等,然后运行Generator的主类即可。 MyBatis Generator在代码生成过程中,会自动生成对应的Java POJO(Plain Old Java Object)类,该类与数据库表的字段一一对应,方便了与数据库的交互操作。同时,它也会生成Mapper接口,其中包含了常见的增删改查操作的方法,开发者可以直接调用这些方法来操作数据库。此外,MyBatis Generator还会生成XML映射文件,这个文件定义了SQL语句与Java方法的对应关系,方便了执行数据库操作。 MyBatis Generator插件的优点是节省了开发人员大量手写重复代码的时间,提高了开发效率。它还遵循了MyBatis的设计哲学,减少了代码的冗余和复杂性。另外,MyBatis Generator可以与其他代码生成插件配合使用,例如Spring Boot的Generator插件,可以进一步简化开发工作。 总结来说,MyBatis Generator插件是一个方便且高效的代码生成工具,它能够根据数据库表结构自动生成与数据库交互所需的Java模型对象、Mapper接口和XML映射文件,大大减少了开发人员的工作量,并提高了代码的可维护性和稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值