澳门新蒲京娱乐


sizeclass中CAR和机型的关系总结【澳门新蒲京娱乐】,Autolayout使用学习

宝剑锋从磨砺出,ITIL和IT运维管理的

通过实现CommentGenerator接口的方法来实现

Mybatis逆工程(下),mybatis工程

    
上一篇文章主要是讲了mybatis-generator-core-1.3.2.jar的使用,这一篇我要介绍的是,修改jar包代码,实现生成自定义模板。

     1.我们从这里可以下载mybatis-generator-core-1.3.2.jar项目源码 

     2.在eclipse下导入存在的maven项目,File->Import

    图片 1

    图片 2

   选择项目源码位置,点finish完成导入。

   图片 3

     项目目录结构大概这样子。

     3.下面我逆工程要生成的mapping和xml格式。

     图片 4

图片 5

图片 6

    4.开始修改,首先说明一下各目录

    图片 7

         
最底边的tse包是我自定义的包,里面是个主类,测试生成的代码是否达到预期标准。

         
由于这个架包是老外写的,生成的代码风格和我们不大一一样,如果你想修改代码格式,建议你看一下菠萝大象的文章,我这里就不讲代码格式了。

         

         
首先,我们先修改逆工程要生成的接口文件mapping的代码,默认情况下有增删改查,我们讲其中一个改方法update吧

          比如 我要让生成的mapping中有这样的一个方法  void
update(Map<String, Object> dataMap);

         
就修改org.mybatis.generator.codegen.mybatis3.javamapper.elements包下的UpdateByPrimaryKeyWithoutBLOBsMethodGenerator类,如下:

         

/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.mybatis.generator.codegen.mybatis3.javamapper.elements;

import java.util.Set;
import java.util.TreeSet;

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.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;

/**
 * 
 * @author Jeff Butler
 * 
 */
public class UpdateByPrimaryKeyWithoutBLOBsMethodGenerator extends
        AbstractJavaMapperMethodGenerator {

    public UpdateByPrimaryKeyWithoutBLOBsMethodGenerator() {
        super();
    }

    @Override
    public void addInterfaceElements(Interface interfaze) {
        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        FullyQualifiedJavaType parameterType = new FullyQualifiedJavaType(
                introspectedTable.getBaseRecordType());
        importedTypes.add(parameterType);
        //新增一个方法
        Method method = new Method();
        //添加方法修饰符PUBLIC
        method.setVisibility(JavaVisibility.PUBLIC);
        //设置返回值,这里我用的是自定义的void,无返回值方法 getVoidInstance()
        //FullyQualifiedJavaType类中可以自定义返回值方法,大家可以自己进去添加
        //不想那么麻烦的话,可以   new FullyQualifiedJavaType("void") , 构造函数写上返回类型就行了
        method.setReturnType(FullyQualifiedJavaType.getVoidInstance());
        //设置方法名,同样可以自己进去看
        method.setName(introspectedTable.getUpdateByPrimaryKeyStatementId());

        //method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$
        FullyQualifiedJavaType mapType=FullyQualifiedJavaType.getMyMapInstance();
        //方法的参数,这里是Map类型的dateMap参数
        Parameter parameter = new Parameter(mapType, "dataMap");
        method.addParameter(parameter);


        context.getCommentGenerator().addGeneralMethodComment(method,
                introspectedTable);

        addMapperAnnotations(interfaze, method);

        if (context.getPlugins()
                .clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method,
                        interfaze, introspectedTable)) {
            interfaze.addImportedTypes(importedTypes);
            interfaze.addMethod(method);
        }
    }

    public void addMapperAnnotations(Interface interfaze, Method method) {
        return;
    }
}

大家可以根据注释来修改。

接下来修改mapping对应的xml中的代码,同样的,这里我只介绍修改update方法,相信看完你就能自己修改其它方法。

就修改org.mybatis.generator.codegen.mybatis3.xmlmapper.elements包下的UpdateByPrimaryKeyWithoutBLOBsElementGenerator类,如下:

/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;

import java.util.Iterator;
import java.util.List;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;

/**
 * 
 * @author Jeff Butler
 * 
 */
public class UpdateByPrimaryKeyWithoutBLOBsElementGenerator extends
        AbstractXmlElementGenerator {

    //private boolean isSimple;

    public UpdateByPrimaryKeyWithoutBLOBsElementGenerator(boolean isSimple) {
        super();
        //this.isSimple = isSimple;
    }

    @Override
    public void addElements(XmlElement parentElement) {
        //update标签(方法最外层)
        XmlElement answer = new XmlElement("update"); //$NON-NLS-1$
        //update标签的属性
        answer.addAttribute(new Attribute(
                "id", introspectedTable.getUpdateByPrimaryKeyStatementId())); //$NON-NLS-1$
        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
                "Map"));
        //把标签加进去
        context.getCommentGenerator().addComment(answer);

        StringBuilder sb = new StringBuilder();
        sb.append("update "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());

        //标签内容,即文本元素
        answer.addElement(new TextElement(sb.toString()));
        sb.setLength(0);

        //set标签
        XmlElement setElement = new XmlElement("set"); //$NON-NLS-1$
        //获取数据库表中的所有字段
        List <IntrospectedColumn> cols=introspectedTable.getAllColumns();
        //迭代
        java.util.Iterator<IntrospectedColumn> iter =cols.iterator();
        while (iter.hasNext()) {//迭代
            //迭代到某一字段
            IntrospectedColumn introspectedColumn = iter.next();
            //if标签
            XmlElement ifElement = new XmlElement("if"); //$NON-NLS-1$
            //字段名
            String str=MyBatis3FormattingUtilities
            .getEscapedColumnName(introspectedColumn);
            //if标签添加属性test,值为           字段 !=null and 字段!=''
            ifElement.addAttribute(new Attribute("test",str+" != null and "+str+"!='' "));

            //if标签内容 ,文本元素,给字段赋予即将修改的值
            sb.append(MyBatis3FormattingUtilities
                    .getEscapedColumnName(introspectedColumn));
            sb.append(" = "); //$NON-NLS-1$
            sb.append(MyBatis3FormattingUtilities
                    .getParameterClause(introspectedColumn));
            if (iter.hasNext()) {
                sb.append(',');
            }

            //if标签添加上面的文本元素
            ifElement.addElement(new TextElement(sb.toString()));
            if (iter.hasNext()) {
                sb.setLength(0);
                OutputUtilities.xmlIndent(sb, 1);
            }
            setElement.addElement(ifElement);
        }

        //where元素(修改的字段前提条件)
        XmlElement whereElement =new XmlElement("where");

        for (IntrospectedColumn introspectedColumn : introspectedTable
                .getPrimaryKeyColumns()) {//遍历表中字段进行判断
            sb.setLength(0);
            sb.append(MyBatis3FormattingUtilities
                    .getEscapedColumnName(introspectedColumn));
            sb.append(" = "); //$NON-NLS-1$
            sb.append(MyBatis3FormattingUtilities
                    .getParameterClause(introspectedColumn));
            whereElement.addElement(new TextElement(sb.toString()));
        }

        //方法中最外层xml元素 update元素添加set元素和where元素
        answer.addElement(setElement);
        answer.addElement(whereElement);

        if (context.getPlugins()
                .sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(answer,
                        introspectedTable)) {
            parentElement.addElement(answer);
        }
    }
}

其它方法大家可以根据这个update方法改。

如果要添加新方法的话参考下面这个帖子

下面我来验证修改成果

generatorConfig.xml //先配置xml    放在src/main/resources/   目录下

<?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>  
    <!-- 引入配置文件 -->  


    <!-- 指定数据连接驱动jar地址 -->  
    <classPathEntry location="E:\eclipse_workspace\testMybatis\mysql-connector-java-5.1.13-bin.jar" />  

    <!-- 一个数据库一个context -->  
    <context id="infoGuardian" targetRuntime="MyBatis3">  
        <!-- 注释 -->  
        <commentGenerator >  
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->  
        </commentGenerator>  

        <!-- jdbc连接 -->  
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"  
            connectionURL="jdbc:mysql://localhost:3306/login?characterEncoding=UTF-8" userId="root"  
            password="root" />  

        <!-- 类型转换 -->  
        <javaTypeResolver>  
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->  
            <property name="forceBigDecimals" value="false"/>  
        </javaTypeResolver>  

        <!-- 生成实体类地址 -->    
        <javaModelGenerator targetPackage="pojo"  
            targetProject="mybatis3" >  
            <!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] -->  
            <property name="enableSubPackages" value="true"/>  
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->  
            <property name="trimStrings" value="true"/>  
        </javaModelGenerator>  

        <!-- 生成mapxml文件 -->  
        <sqlMapGenerator targetPackage="mapper" 
            targetProject="mybatis3" >  
            <!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] -->  
            <property name="enableSubPackages" value="true" />  
        </sqlMapGenerator>  

        <!-- 生成mapxml对应client,也就是接口dao -->      
        <javaClientGenerator type="XMLMAPPER" targetPackage="mapper"  
            targetProject="mybatis3">  
            <!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] -->  
            <property name="enableSubPackages" value="true" />  
        </javaClientGenerator>  

        <!-- 配置表信息,这里没生成一张表,这里需要改变一次对应表名 -->    
         <table tableName="login"  
            domainObjectName="Login" enableCountByExample="false"  
            enableDeleteByExample="false" enableSelectByExample="false"  
            enableUpdateByExample="false">  
          </table> 

    </context>  
</generatorConfiguration> 

StartUp.java//验证的主程序

package tse;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class StartUp {

    public static void main(String []args)throws Exception{
        List<String> warnings = new ArrayList<String>();
        File configFile=new File(StartUp.class.getResource("/generatorConfig.xml").toURI());
        ConfigurationParser cp = new ConfigurationParser(warnings);

        Configuration config = cp.parseConfiguration(configFile);

        DefaultShellCallback shellCallback = new DefaultShellCallback(true);


            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
            myBatisGenerator.generate(null);
            System.out.println(warnings);
    }
}

好了,运行StartUp.java

图片 8

就根据generatorConfig.xml的配置在目标目录生成对应文件。

OK,和我预期结果一样。

5.上面修改完了,我们开始打包。

由于是个maven项目,我用的是maven3.3.9,大家也可以用eclipse内置的maven,反正我是不喜欢。

下面是我maven项目的pom.xml文件代码

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2009-2011 The MyBatis Team

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<!--
  version: $Id: pom.xml 4114 2011-11-27 19:03:32Z simone.tripodi $
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

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

  <artifactId>mybatis-generator-core</artifactId>
  <packaging>jar</packaging>
  <name>MyBatis Generator Core</name>

  <build>
    <!-- this build creates and installs an instrumented JAR file
         for use by the systests projects - so we can gather
         consolidated coverage information
    -->
    <plugins>
     <!--  <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-site-plugin</artifactId>
          <executions>
            <execution>
              <phase>prepare-package</phase>
              <goals>
                <goal>site</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>
      </plugin> -->
      <!-- <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-source-plugin</artifactId>
          <version>2.2.1</version>
          <executions>
            <execution>
              <id>attach-sources</id>
              <goals>
                <goal>jar</goal>
              </goals>
              <configuration>
              <includes>
              <include>**/org/**</include>
              </includes>
              </configuration>
            </execution>
          </executions>
      </plugin> -->
     <!-- <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-javadoc-plugin</artifactId>
          <executions>
            <execution>
              <phase>prepare-package</phase>
              <goals>
                <goal>jar</goal>
              </goals>
            </execution>
          </executions>
      </plugin> -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>cobertura-instrument</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>instrument</goal>
            </goals>
          </execution>
        </executions>      
      </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>
        <executions>
          <execution>
            <id>cobertura-jar</id>
            <phase>integration-test</phase>
            <goals>
              <goal>jar</goal>
            </goals>
            <configuration>
              <classifier>cobertura</classifier>
              <classesDirectory>${basedir}/target/generated-classes/cobertura</classesDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin> -->

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>attach-jar</id>
            <phase>integration-test</phase>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <archive>
            <manifest>
            <addClasspath>true</addClasspath>
            <classpathPrefix></classpathPrefix>
              <mainClass>org.mybatis.generator.api.ShellRunner</mainClass>
            </manifest>
          </archive>
          <includes>
              <include>**/org/**</include>
              </includes>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <executions>
          <execution>
            <id>cobertura-install</id>
            <phase>integration-test</phase>
            <goals>
              <goal>install</goal>
            </goals>
            <configuration>
              <classifier>cobertura</classifier>
            </configuration>
          </execution>
        </executions>      
      </plugin>

      <!-- <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptors>
            <descriptor>${basedir}/src/main/assembly/src.xml</descriptor>
          </descriptors>
        </configuration>            
        <executions>
          <execution>
            <id>bundle</id>
            <goals>
              <goal>single</goal>
            </goals>
            <phase>package</phase>
          </execution>
        </executions>
      </plugin> -->

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <appendAssemblyId>false</appendAssemblyId>
          <descriptors>
          <descriptor>${basedir}/src/main/assembly/src.xml</descriptor>
          </descriptors>
        </configuration>            
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>com.googlecode.maven-gcu-plugin</groupId>
        <artifactId>maven-gcu-plugin</artifactId>
        <executions>
          <execution>
            <phase>deploy</phase>
            <goals>
              <goal>upload</goal>
            </goals>
            <configuration>
              <uploads>
                <upload>
                  <file>${project.build.directory}/${project.artifactId}-${project.version}-bundle.zip</file>
                  <summary>MyBatis Generator ${project.version}</summary>
                  <labels>
                    <label>Featured</label>
                    <label>Type-Archive</label>
                    <label>Product-Generator</label>
                    <label>Version-${project.version}</label>
                  </labels>
                </upload>
              </uploads>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <configuration>
          <arguments>-Prelease,gupload</arguments>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jdepend-maven-plugin</artifactId>
        <version>2.0-beta-2</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </reporting>

  <dependencies>
   <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.ant</groupId>
      <artifactId>ant</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hsqldb</groupId>
      <artifactId>hsqldb</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12</version>
        </dependency>
  </dependencies>

  <scm>
    <url>https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core</url>
    <connection>scm:svn:https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core</connection>
    <developerConnection>scm:svn:https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core</developerConnection>
  </scm> 
</project>

然后是修改src/main/assembly/src.xml代码

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <id>bundle</id>
  <formats>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
      <directory>src/main/resources</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>generatorConfig.xml</include>
      </includes>
      <excludes>
      <exclude>log4j.properties</exclude>
      <exclude>src.xml</exclude>
      </excludes>
    </fileSet>

    <fileSet>
      <directory>src/main/scripts</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>run.bat</include>
      </includes>
    </fileSet>

    <fileSet>
      <directory>${project.build.directory}</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>${project.artifactId}-${project.version}.jar</include>
      </includes>
    </fileSet>
    <fileSet>
      <directory>${project.build.directory}</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>${project.artifactId}-${project.version}-sources.jar</include>
      </includes>
    </fileSet>
  </fileSets>
</assembly>

接下来,在src/main/  
下面新建scripts文件夹,在scripts文件夹新建txt文本文档,输入以下代码

java -jar mybatis-generator-1.3.2.jar -configfile generatorConfig.xml
–overwrite
pause

改文件名为run.bat

至此,打包配置完毕。

大家可以在项目下右键Run as->maven build  
在goal里输入package。或者命令行cmd中 进入项目的目录,运行mvn
package,这里第一次运行会等待很久,因为maven会下载依赖的jar包,请耐心等待。

打包完毕,就会在项目根目录下的target目录生成如下结构

图片 9

 从上图中我们可以看到mybatis-generator-core-1.3.2.jar包已经生成。接下来我们可以用它加上generatorConfig.xml来生成自己想要的代码。

 如果修改代码过程中有什么不懂的,请多看源代码。

 OK,晒下成果图

 图片 10 图片 11  

  本文就讲到这里!

 

上一篇文章主要是讲了mybatis-generator-core-1.3.2.jar的使用,这一篇我要介绍的是,修改jar包代码,实现生成自定义…

自己手动实现的前提,对maven项目有基本的了解,在本地成功搭建了maven环境,可以参考我之前的文章:maven环境搭建

项目里新建表时model,mapper以及mapper.xml基本都是用Mybatis
Generator(以下简称为MBG)自动生成的,但是MBG自动生成的model的注释实在有点非人类,至少中国人是完全接受不了的,在配置中禁用掉注释吧,倒是简单了,可是生成的model类光秃秃的,啥都没有,字段方法没有注释,使用很不方便,别人看也不知道这个字段是啥含义,到最后还是要自己添加,一张表多点几十个字段,特么添加累死了,不能这么干,得想法子,百度了一下网上,基本有两种方法,第一种,就是直接修改MGB的源代码,第二种就是自己写一个类实现CommentGenerator接口,先说自己写一个新类实现CommentGenerator接口的方法来使自动生成的model类含有中文注释吧.

  • 1.首先新建一个maven项目,请选择一个简单的maven项目:或者在选择的时候直接选择create
    a simple project.

图片 12

  • 2,右键项目->build path->config build
    path…->Libraries,修改jdk为你工作空间的默认jdk,然后右键项目->new->source
    folder,输入src/main/resources,建好resources目录,如果已经建好就直接跳过.这里最好不要忘记,否则有的时候建立默认jdk是1.5的,运行可能会有莫名其妙的问题.

  • 3 因为是要写一个类实现CommentGenerator接口,所以先在项目中引入mybatis-generator-core的jar包
    在pom.xml中添加依赖,
    这里统一使用1.3.2版本.为了不用每次使用都要使用者自己指定ojdbc6.jar位置,直接将其引入到项目中,这里要使用该引入,需要先将jar包安装到本地maven仓库中,否则这里这样引入会报错的,怎么安装可以参考这篇文章:

    maven手动安装jar包到本地仓库,以ojdbc6为例,

   同时为了支持mysql,也一起加入mysql的驱动包,mysql的驱动包不用手动安装,直接引入就会自动下载的

<dependency>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-core</artifactId>
     <version>1.3.2</version>
</dependency>
<dependency>
     <groupId>com.oracle</groupId>
     <artifactId>ojdbc6</artifactId>
     <version>6.0</version>
</dependency>
<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>5.1.9</version>
</dependency>
  • 4
    在源代码中新建一个类MyCommentGenerator,实现CommentGenerator接口,类的代码如下:

图片 13图片 14

package org.mybatis.generator;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;

/**
 * 描述:
 * @since 1.9.10
 * @version 1.9.10
 * @作者:niexiaohui
 * @创建时间:2016年11月22日
 * @修改记录:
 */
public class MyCommentGenerator implements CommentGenerator{
    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;

    public MyCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    public void addJavaFileComment(CompilationUnit compilationUnit) {
        // add no file level comments by default
        return;
    }

    /**
     * Adds a suitable comment to warn users that the element was generated, and
     * when it was generated.
     */
    public void addComment(XmlElement xmlElement) {
        return;
    }

    public void addRootComment(XmlElement rootElement) {
        // add no document level comments by default
        return;
    }

    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);

        suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));

        suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do
     * not wish to include the Javadoc tag - however, if you do not include the
     * Javadoc tag then the Java merge capability of the eclipse plugin will
     * break.
     * 
     * @param javaElement
     *            the java element
     */
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag
     * and XML comments. You may return null if you do not want the date in
     * these documentation elements.
     * 
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        String result = null;
        if (!suppressDate) {
            result = currentDateStr;
        }
        return result;
    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        sb.append(" ");
        sb.append(getDateString());
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        innerClass.addJavaDocLine(" */");
    }

    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerEnum.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString().replace("\n", " "));
        innerEnum.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        field.addJavaDocLine(sb.toString().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        field.addJavaDocLine(sb.toString().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
      method.addJavaDocLine("/**");
      addJavadocTag(method, false);
      method.addJavaDocLine(" */");
    }

    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    public void addSetterComment(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        Parameter parm = method.getParameters().get(0);
        sb.setLength(0);
        sb.append(" * @param ");
        sb.append(parm.getName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(" */");
    }
}

View Code

  • 5.再新建一个类StartUp,用于运行项目,类的代码如下:

图片 15图片 16

package org.mybatis.generator;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

/**
 * 描述:
 * @since 1.9.10
 * @version 1.9.10
 * @作者:niexiaohui
 * @创建时间:2016年11月22日
 * @修改记录:
 */
public class StartUp {
    public static void main(String[] args) throws URISyntaxException {
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("generatorConfig.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();
        }
    }
}

View Code

  • 6.
    然后将generatorConfig.xml放入resources目录下,generatorConfig.xml内容如下


    <!-- ojdbc6.jar已经直接放到项目中,无需指定了,同时mysql驱动包也一样,这里同样无需指定 -->
    <!-- <classPathEntry location="ojdbc6.jar" /> -->
    <context id="context1" targetRuntime="MyBatis3">
        <!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 这里的type里写的是你的实现类的类全路径 -->
        <commentGenerator type="org.mybatis.generator.MyCommentGenerator">
        </commentGenerator>
    
        <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
            connectionURL="jdbc:oracle:thin:@远程ip地址或localhost:1521:orcl" userId="用户名"
            password="密码">
            <!-- 针对oracle数据库 -->
            <property name="remarksReporting" value="true"></property>
        </jdbcConnection>
    

        
        
           

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
    
        <!-- dto class -->
        <javaModelGenerator targetPackage="model"
            targetProject="C:\Users\Administrator\Desktop">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
    
        <!-- mybatis xml file -->
        <sqlMapGenerator targetPackage="dao"
            targetProject="C:\Users\Administrator\Desktop">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
    
        <!-- mapper class -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="dao" targetProject="C:\Users\Administrator\Desktop">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
    
        <!--不生成帮助类(Exmaples) -->
        <!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" 
            enableSelectByExample="false" selectByExampleQueryId="false" -->
        <!--已生成的表 <table schema="demo" tableName="USER" domainObjectName="User"></table> -->
        <table schema="" tableName="ABS_DEAL" domainObjectName="AbsDeal"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>

到此为止项目的结构如下:

图片 17

相关文章

No Comments, Be The First!
近期评论
    功能
    网站地图xml地图