扩展mybatis-generator自动生成代码项目

简介: 通用的新增方法通用的分页方法通用的修改方法

项目结构预览

实现功能

  1. 通用的新增方法
  2. 通用的分页方法
  3. 通用的修改方法

注意事项

  • 需要修改的位置

generatorConfig.properties文件中

  1. 项目路径
  2. jdbcConnection 连接的相关配置

generatorConfig.xml文件中

  1. 生成对应表及类名 这个配置需要修改,你需要对哪些表生产代码就添加哪些表

运行

直接运行GeneratorStartUp类即可

相关扩展介绍

1自定义文档注释

由于 mybatis-generator 自带的文档注释对我们中国人不太友好。为了项目需要,我在此项目中扩展了一下文档注释。

首先,我自定义了MyCommentGenerator类,其继承自DefaultCommentGenerator 在该类中我们需要以下几个方法

2addGeneralMethodComment 方法,该方法用于给方法添加文档注释

3addFieldComment 方法,该方法用于给属性添加文档注释

4addGetterComment,addSetterComment这两个方法分别是给get,set方法添加文档注释

5做好这些之后,我们需要修改一下generatorConfig.xml中的配置<commentGenerator type="com.jay.generator.internal.MyCommentGenerator"> <property name="javaFileEncoding" value="UTF-8"/> </commentGenerator>

6配置属性化

原有的mybatis-generator的工具,相关的配置个人感觉不是很方便。所以我也做了相应的修改。

首先,新建一个属性文件,如generatorConfig.properties

然后把相关配置放在该属性文件中:

如:

driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/ssh_employee?useUnicode\=true&characterEncoding\=UTF-8
user=root
password=1234

我们先在generatorConfig.xml添加properties

<properties resource="generatorConfig.properties"></properties>

然后就可以使用相关的key,如: <jdbcConnection driverClass="${driverClass}" connectionURL="${jdbcUrl}" userId="${user}" password="${password}">

3. 添加自定义方法

到了最重要的一个环节,当mybatis-generator自动内置的方法不满足我们的需求的时候,我们可以扩展自定义方法。步骤如下:

1. 自定义类MyIntrospectedTableMyBatis3SimpleImpl 继承IntrospectedTableMyBatis3SimpleImpl,如下:

/**
     * XML的生成方法
     * @param javaClientGenerator
     * @param warnings
     * @param progressCallback
     */
    @Override
    protected void calculateXmlMapperGenerator(AbstractJavaClientGenerator javaClientGenerator, List<String> warnings, ProgressCallback progressCallback) {
        this.xmlMapperGenerator = new MySimpleXMLMapperGenerator();
        this.initializeAbstractGenerator(this.xmlMapperGenerator, warnings, progressCallback);
    }
    /**
     * Mapper类的生成方法
     * @return
     */
    @Override
    protected AbstractJavaClientGenerator createJavaClientGenerator() {
        if (this.context.getJavaClientGeneratorConfiguration() == null) {
            return null;
        } else {
            String type = this.context.getJavaClientGeneratorConfiguration().getConfigurationType();
            Object javaGenerator;
            if ("XMLMAPPER".equalsIgnoreCase(type)) {
                javaGenerator = new MySimpleJavaClientGenerator();
            } else if ("ANNOTATEDMAPPER".equalsIgnoreCase(type)) {
                javaGenerator = new MySimpleAnnotatedClientGenerator();
            } else if ("MAPPER".equalsIgnoreCase(type)) {
                javaGenerator = new MySimpleJavaClientGenerator();
            } else {
                javaGenerator = (AbstractJavaClientGenerator) ObjectFactory.createInternalObject(type);
            }
            return (AbstractJavaClientGenerator)javaGenerator;
        }
    }
    /**
     * model类的生成方法
     * @param warnings
     * @param progressCallback
     */
    @Override
    protected void calculateJavaModelGenerators(List<String> warnings, ProgressCallback progressCallback) {
        super.calculateJavaModelGenerators(warnings, progressCallback);
    }


分别新建:MySimpleXMLMapperGenerator类,MySimpleJavaClientGenerator类,用于生成xml文件和mapper文件。

3. MySimpleXMLMapperGenerator 类继承SimpleXMLMapperGenerator类重写getSqlMapElement方法

@Override
    protected XmlElement getSqlMapElement() {
        FullyQualifiedTable table = this.introspectedTable.getFullyQualifiedTable();
        this.progressCallback.startTask(Messages.getString("Progress.12", table.toString()));
        XmlElement answer = new XmlElement("mapper");
        String namespace = this.introspectedTable.getMyBatis3SqlMapNamespace();
        answer.addAttribute(new Attribute("namespace", namespace));
        this.context.getCommentGenerator().addRootComment(answer);
        this.addResultMapElement(answer);
        this.addDeleteByPrimaryKeyElement(answer);
        this.addInsertElement(answer);
        this.addUpdateByPrimaryKeyElement(answer);
        this.addSelectByPrimaryKeyElement(answer);
        this.addSelectAllElement(answer);
        this.addCountListElement(answer);
        this.addQueryPageListElement(answer);
        return answer;
    }


4.MySimpleJavaClientGenerator 类继承SimpleJavaClientGenerator类重写getCompilationUnits方法,如

@Override
    public List<CompilationUnit> getCompilationUnits() {
        this.progressCallback.startTask(Messages.getString("Progress.17", this.introspectedTable.getFullyQualifiedTable().toString()));
        CommentGenerator commentGenerator = this.context.getCommentGenerator();
        FullyQualifiedJavaType type = new FullyQualifiedJavaType(this.introspectedTable.getMyBatis3JavaMapperType());
        Interface interfaze = new Interface(type);
        interfaze.setVisibility(JavaVisibility.PUBLIC);
        //添加添加类注释,这个是添加到类头部,没有多大作用
        commentGenerator.addJavaFileComment(interfaze);
        String rootInterface = this.introspectedTable.getTableConfigurationProperty("rootInterface");
        if (!StringUtility.stringHasValue(rootInterface)) {
            rootInterface = this.context.getJavaClientGeneratorConfiguration().getProperty("rootInterface");
        }
        if (StringUtility.stringHasValue(rootInterface)) {
            FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(rootInterface);
            interfaze.addSuperInterface(fqjt);
            interfaze.addImportedType(fqjt);
        }
        this.addDeleteByPrimaryKeyMethod(interfaze);
        this.addInsertMethod(interfaze);
        this.addSelectByPrimaryKeyMethod(interfaze);
        this.addSelectAllMethod(interfaze);
        this.addUpdateByPrimaryKeyMethod(interfaze);
        this.addCountListMethod(interfaze);
        this.addQueryPageListMethod(interfaze);
        List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
        if (this.context.getPlugins().clientGenerated(interfaze, (TopLevelClass) null, this.introspectedTable)) {
            answer.add(interfaze);
        }
        List<CompilationUnit> extraCompilationUnits = this.getExtraCompilationUnits();
        if (extraCompilationUnits != null) {
            answer.addAll(extraCompilationUnits);
        }
        return answer;
    }

generatorConfig.xml的几点说明

1.table 的配置的相关属性说明:<table tableName="sh_department" domainObjectName="ShDepartment" enableInsert="true" enableDeleteByPrimaryKey="false" enableUpdateByPrimaryKey="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" selectByPrimaryKeyQueryId="false"></table>

说明:tableName="sh_department" 表示表名为sh_department,

domainObjectName="ShDepartment"表示实体类(model)的名称为ShDepartment

enableInsert="true" 表示 生成 insert方法

enableDeleteByPrimaryKey="false"表示不生成deleteByPrimaryKey方法

所以 enablexxx="false"为true表示生成某方法,为false表示不生成某方法。

mybatis-generator-core相关技术探究

项目结构介绍

api包主要提供外部接口,供扩展使用,切入点可以试MyPluginAdapter类

codegen 包是生成文件的核心包,入口是IntrospectedTableMyBatis3Impl类,生成对应文件文件需要的类在对应的

子包中,如:生成xml文件相关的类在 xmlmapper包中。

internal 包下 DefaultCommentGenerator 类是用于生成对应的文档注释。可以扩展,扩展之后再修改一下generatorConfig.xml

mybatis-generator-core相关技术探究

项目结构介绍

api包主要提供外部接口,供扩展使用,切入点可以试MyPluginAdapter类

codegen 包是生成文件的核心包,入口是IntrospectedTableMyBatis3Impl类,生成对应文件文件需要的类在对应的

子包中,如:生成xml文件相关的类在 xmlmapper包中。

internal 包下 DefaultCommentGenerator 类是用于生成对应的文档注释。可以扩展,扩展之后再修改一下generatorConfig.xml

涉及到的设计模式

适配器模式
具体的适配器模式可以参考:设计模式学习06----之适配器模式

工厂方法模式:7200889d1a2530a3e5f574989831f5c4_70.png

具体的工厂方法模式可以参考:设计模式学习04----之简单工厂模式以及工厂方法模式以及抽象工厂模式

参考文档:

http://www.mybatis.org/generator/index.html

资源下载

http://download.csdn.net/download/u014534808/10174149


相关文章
|
4月前
|
Java 关系型数据库 数据库连接
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
|
12天前
|
XML Java 数据库连接
mybatis plus模板快速生成代码
MybatisX 是一款提升开发效率的 IDEA 插件,尤其适用于处理多表情况。通过 MybatisX-Generator,用户能轻松生成实体类、服务类、Mapper 接口及 XML 文件,显著减少工作量。安装步骤简便:通过 File -&gt; Settings -&gt; Plugins -&gt; Browse Repositories 完成搜索与安装流程。集成数据库后,右键所需操作的数据表,选择 MyBatisX-Generator 进行自动化代码生成。更多细节可参考相关教程。
36 0
|
1月前
|
Java 数据库连接 mybatis
成功解决: Invalid bound statement (not found) 在已经使用mybatis的项目里引入mybatis-plus,结果不能共存的解决
这篇文章讨论了在已使用MyBatis的项目中引入MyBatis-Plus后出现的"Invalid bound statement (not found)"错误,并提供了解决方法,主要是通过修改yml配置文件来解决MyBatis和MyBatis-Plus共存时的冲突问题。
成功解决: Invalid bound statement (not found) 在已经使用mybatis的项目里引入mybatis-plus,结果不能共存的解决
|
1月前
|
Java 关系型数据库 MySQL
1、Mybatis-Plus 创建SpringBoot项目
这篇文章是关于如何创建一个SpringBoot项目,包括在`pom.xml`文件中引入依赖、在`application.yml`文件中配置数据库连接,以及加入日志功能的详细步骤和示例代码。
|
1月前
|
SQL Java 数据库连接
springboot+mybatis+shiro项目中使用shiro实现登录用户的权限验证。权限表、角色表、用户表。从不同的表中收集用户的权限、
这篇文章介绍了在Spring Boot + MyBatis + Shiro项目中,如何使用Shiro框架实现登录用户的权限验证,包括用户、角色和权限表的设计,以及通过多个表查询来收集和验证用户权限的方法和代码实现。
springboot+mybatis+shiro项目中使用shiro实现登录用户的权限验证。权限表、角色表、用户表。从不同的表中收集用户的权限、
|
2月前
|
Java 数据库连接 Spring
搭建 spring boot + mybatis plus 项目框架并进行调试
搭建 spring boot + mybatis plus 项目框架并进行调试
60 4
|
1月前
|
druid Java 数据库连接
SpringBoot项目整合MybatisPlus持久层框架+Druid数据库连接池,以及实现增删改查功能
SpringBoot项目整合MybatisPlus和Druid数据库连接池,实现基本的增删改查功能。
158 0
|
3月前
|
Java 数据库连接 数据库
大事件后端项目05-----springboot整合mybatis
大事件后端项目05-----springboot整合mybatis
大事件后端项目05-----springboot整合mybatis
|
3月前
|
SQL 前端开发 Java
我这样写代码,比直接使用 MyBatis 效率提高了 100 倍
Mybatis Hibernate 等都是我们常用的 ORM, 它们有时候很好用,但某些场景下也很繁琐,比如下文要讲的一个需求,最后本文会给出比直接用这些 ORM 开发效率至少提高 100 倍的方法...
45 1
我这样写代码,比直接使用 MyBatis 效率提高了 100 倍
|
2月前
|
Java 数据库连接 Maven
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类