Mybatis Generator

2019-09-25  本文已影响0人  十二找十三
<plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
               <overwrite>true</overwrite> 
        </configuration>
 </plugin>

以下基于源码修改 mybatis-generator-core-1.3.2.jar
关于官方的Mybatis Generator就不做叙述了 本文目的生成自定义的文件 以生成自定义Controller为例

1.关于 mybatis-generator-core 源码的pom 的问题

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator</artifactId>
        <version>1.3.5</version>
    </parent>

    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.2</version>

    <packaging>jar</packaging>
    <name>ccbckj Generator</name>

    <properties>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <pluginManagement>
        <plugins>
            <!-- Javadoc -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <show>public</show>
                    <charset>UTF-8</charset>
                    <encoding>UTF-8</encoding>
                    <docencoding>UTF-8</docencoding>
                    <additionalOptions>
                        <additionalOption>-Xdoclint:none</additionalOption>
                    </additionalOptions>
                </configuration>
            </plugin>

            <!-- GPG -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <phase>verify</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <attach>true</attach>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>org.mybatis.generator.api.ShellRunner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
        </pluginManagement>
    </build>

    <dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>provided</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.43</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>
</project>

1.pluginManagement 标签是出现 Unable to execute gpg command: Error while executing process. Cannot run program "gpg": error=2, No such file or directory -> [Help 1] 这个错误添加上的 应该是你的maven版本是3以上 导致打包不对 所以你可以添加这个标签

  1. 自定义
1.
在你的generatorConfig.xml 配置文件添加
        <!-- 生成Controller的包名和位置 -->
        <plugin type="org.mybatis.generator.plugins.MybatisControllerPlugin">
            <property name="targetPackage" value="com.cc.ys.controller"/>
            <property name="targetProject" value="src/main/java"/>
        </plugin>
2.
  2.1
    看好你上面自定义插件的type type="org.mybatis.generator.plugins.MybatisControllerPlugin"
    所以在org.mybatis.generator.plugins包下创建MybatisControllerPlugin这个java类

    public class MybatisControllerPlugin extends PluginAdapter   // 继承这个父类就行

  2.2
    重写两个最重要的方法

    @Override
    public boolean validate(List<String> warnings) {
        properties.getProperty("targetPackage");  // 看看你自定义插件的两个属性 在这里可以获取到值
        properties.getProperty("targetProject");
        return true;
    }
    

     @Override
     public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
         introspectedTable.getBaseRecordType();// 这个方法能获取到你生成的实体类名字
        
        ....
        // 添加 service属性
        Field serviceField = new Field();
        serviceField.setName(toLowerCase(objType.getShortName()) + "Service");
        serviceField.setType(new FullyQualifiedJavaType(objType.getShortName() + "Service")); // 类型
        serviceField.setVisibility(JavaVisibility.PRIVATE);
        serviceField.addAnnotation("@Autowired");
        controller.addField(serviceField);
        

        // 添加方法
        controller.addMethod(addInsertMethod());
        ...        


        GeneratedJavaFile file = new GeneratedJavaFile(controller, targetProject, context.getJavaFormatter());// 关于第一个参数controller 类型为 TopLevelClass
        files.add(file);
        return files;
     } 


    /**
     * 添加新增方法
     */
    protected Method addInsertMethod() {
        String objName = toLowerCase(objType.getShortName());
        Method method = new Method();

        method.setName("insert");
        method.setReturnType(new FullyQualifiedJavaType("Map<String, Object>"));
        method.setVisibility(JavaVisibility.PUBLIC);
        method.addAnnotation("@PostMapping(value = \"/\")");

        FullyQualifiedJavaType tmp1 = new FullyQualifiedJavaType(objType.getShortName());
        Parameter p1 = new Parameter(tmp1, objName);
        method.addParameter(p1);

        StringBuilder sb = new StringBuilder();
        sb.append("return ");
        sb.append(objName + "Service.");
        sb.append("addSelective(");
        sb.append(objName);
        sb.append(");");
        method.addBodyLine(sb.toString());

        return method;
    }   
  1. 一些相关细节
  1. 你要生成的类 就用TopLevelClass 类型   你要生成的接口 就用Interface 类型  
  2. 
     controller.setVisibility(JavaVisibility.PUBLIC);  // 设置类或者接口的权限API
     controller.addSuperInterface(new FullyQualifiedJavaType("BaseController")); // 自定义类实现API implements
     controller.setSuperClass(new FullyQualifiedJavaType("BaseController")); // 自定义类实现API extends
     controller.addAnnotation("@RestController");// 注解API
     controller.addImportedType(new FullyQualifiedJavaType("java.util.Map")); //导包API
     controller.addField(serviceField);// 添加属性API
     controller.addMethod(addSelectListMethod());// 添加方法API
 
 3.关于缩进空格问题
     org.mybatis.generator.api.dom.OutputUtilities  在这个类里面

    public static void javaIndent(StringBuilder sb, int indentLevel) {
        for (int i = 0; i < indentLevel; i++) {
            sb.append("    ");// 以前是两个空格 现在我给改成4个了
        }
    }
  1. 修改自定义XML
org.mybatis.generator.codegen.mybatis3.xmlmapper.XMLMapperGenerator 改这个类里面的源码就好

5.test
generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry location="/Users/cuimiao/Desktop/mysql.jar"/>

    <!-- id:ccbckj 随意起的名字-->
    <context id="ccbckj" targetRuntime="MyBatis3">

        <!-- dataTable 类-->
        <property name="dataTablePackage" value="com.bc.mcode.model"/>

        <!-- 基础框架 类-->
        <property name="basePackage" value="com.bc.mcode.base"/>

        <!-- 插件 : 生成的Java模型创建一个toString方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <!-- 生成service的包名和位置 -->
        <plugin type="org.mybatis.generator.plugins.MybatisServicePlugin">
            <property name="targetPackage" value="com.bc.mcode.service"/>
            <property name="implementationPackage" value="com.bc.mcode.service.impl"/>
            <property name="targetProject" value="src/main/java"/>
        </plugin>

        <!-- 生成service的包名和位置 -->
        <plugin type="org.mybatis.generator.plugins.MybatisControllerPlugin">
            <property name="targetPackage" value="com.bc.mcode.controller"/>
            <property name="targetProject" value="src/main/java"/>
        </plugin>

        <commentGenerator>
            <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://172.16.1.52/ltfkcbsdb" userId="root" password="root19"></jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.bc.mcode.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.bc.mcode.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>



        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名  -->
        <table tableName="bc_ser_role_community" domainObjectName="RoleCommunity1" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

pom.xml 里面添加

<plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
上一篇下一篇

猜你喜欢

热点阅读