MyBatis Generator生成代码的几种方式
阅读原文时间:2021年04月21日阅读:1

由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实体类、DAO接口和Mapper映射文件。这样可以省去一部分的功夫,下面将介绍几种生成方式:

MyBatis Generator 参考文档:

http://blog.csdn.net/isea533/article/details/42102297

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

第一种:使用命令行创建

生成代码需要的文件和jar包:

         

其中有mybatis框架的jar包,数据库驱动程序jar包以及MyBatis生成器jar包。其中的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="mysql-connector-java-5.1.7-bin.jar"/> 

    <!--    
    jdbc.driver=com.mysql.jdbc.Driver
    url=jdbc:mysql:///test
    username=root
    password=123456 
    -->

  <context id="DB2Tables" targetRuntime="MyBatis3">
      <!-- 注释 -->  
    <commentGenerator >  
        <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
        <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
    </commentGenerator>

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql:///test"
        userId="root"
        password="123456">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>



    <!-- 修改包名字 -->
    <javaModelGenerator targetPackage="com.solin.entity" targetProject="../src">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="com.solin.mapper"  targetProject="../src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper"  targetProject="../src">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>


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

</generatorConfiguration>

当以上这些完成之后,只需要打开控制台,进入lib目录下,执行脚本:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite即可。

这样在生成之后,就可以在src目录下找到相应的文件夹,每张表都会对应三个文件(实体类、接口、配置文件)。

最后附上完整demo:http://download.csdn.net/download/qq_32786873/10020288

第二种:通过MybatisGenerator类和配置文件生成代码

项目结构如下:

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="/"/> 

    <!--    
    jdbc.driver=com.mysql.jdbc.Driver
    url=jdbc:mysql:///test
    username=root
    password=123456 
    -->

  <context id="DB2Tables" targetRuntime="MyBatis3">
      <!-- 注释 -->  
    <commentGenerator >  
        <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
        <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
    </commentGenerator>

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql:///test"
        userId="root"
        password="123456">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>



    <!-- 修改包名字 -->
    <javaModelGenerator targetPackage="com.solin.entity" targetProject=".\src">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>


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

</generatorConfiguration>

创建MybatisGeneratorUtil类:

package com.solin;

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 MybatisGeneratorUtil {

    public static void main(String[] args) throws Exception {
           generator();
    }

    private static void generator() throws Exception {
        List<String> warnings = new ArrayList<String>();
           boolean overwrite = true;
           File configFile = new File("generatorConfig.xml");
           ConfigurationParser cp = new ConfigurationParser(warnings);

           Configuration config = cp.parseConfiguration(configFile);
           DefaultShellCallback callback = new DefaultShellCallback(overwrite);
           MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
           myBatisGenerator.generate(null);

           System.out.println("代码生成完毕>>>>>>>>>>>>");
    }

}

执行main方法就可以生成代码了,执行后的结果如下:


最后附上完整demo:http://download.csdn.net/download/qq_32786873/10020408

第三种方式 通过GeneratorAntTask类和配置文件生成

项目结构如下:

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="/"/> 

    <!--    
    jdbc.driver=com.mysql.jdbc.Driver
    url=jdbc:mysql:///test
    username=root
    password=root 
    -->

  <context id="DB2Tables" targetRuntime="MyBatis3">
      <!-- 注释 -->  
    <commentGenerator >  
        <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
        <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
    </commentGenerator>

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql:///test"
        userId="root"
        password="root">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>



    <!-- 修改包名字 -->
    <javaModelGenerator targetPackage="com.solin.entity" targetProject=".\src">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>


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

</generatorConfiguration>

创建GeneratorAntTaskUtil类:

package com.solin;

import org.mybatis.generator.ant.GeneratorAntTask;

public class GeneratorAntTaskUtil {

    public static void main(String[] args) throws Exception {
           generator();
    }

    private static void generator() throws Exception {
       GeneratorAntTask task = new GeneratorAntTask();
       task.setConfigfile("generatorConfig.xml");  //(配置文件具体path)
       task.execute();

       System.out.println("代码生成完毕>>>>>>>>>>>>");
    }

}

执行main方法就可以生成代码了,执行后的结果如下:

最后附上完整demo:http://download.csdn.net/download/qq_32786873/10022347

第四种:基于Maven插件的方式

首先创建一个Maven工程,项目目录如下:

pom.xml文件配置如下:

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.solin</groupId>
  <artifactId>autoGenerate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>autoGenerate</name>
  <url>http://maven.apache.org</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
        <finalName>autoGenerate</finalName>
        <plugins>  
            <plugin>
               <groupId>org.mybatis.generator</groupId>
               <artifactId>mybatis-generator-maven-plugin</artifactId>
               <version>1.3.2</version>
               <executions>
                  <execution>
                     <id>Generate MyBatis Files</id>
                     <goals>
                        <goal>generate</goal>
                     </goals>
                     <phase>generate</phase>
                     <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                     </configuration>
                  </execution>
               </executions>

               <dependencies>
                  <dependency>
                     <groupId>mysql</groupId>
                     <artifactId>mysql-connector-java</artifactId>
                     <version>5.1.38</version>
                  </dependency>
                  <dependency>
                     <groupId>org.mybatis.generator</groupId>
               <artifactId>mybatis-generator-core</artifactId>
                     <version>1.3.5</version>
                  </dependency>

                  <dependency>
                     <groupId>org.mybatis</groupId>
                     <artifactId>mybatis</artifactId>
                     <version>3.4.2</version>
                  </dependency>
               </dependencies>
            </plugin> 
        </plugins>
    </build>
</project>

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>
    <!-- 引入配置文件 -->  
    <properties resource="application.properties"/>

    <!-- 一个数据库一个context -->  
    <context id="MBG" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>

        <!-- 注释 -->  
        <commentGenerator >  
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
            <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
        </commentGenerator>  

        <!-- jdbc连接 -->  
        <jdbcConnection 
            driverClass="${jdbc.driverClassName}"
            connectionURL="${jdbc.url}" 
            userId="${jdbc.username}" 
            password="${jdbc.password}">
        </jdbcConnection>

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

        <!-- 生成实体类地址 -->   
        <javaModelGenerator targetPackage="${package.entity}" targetProject="src/main/java">
            <!-- 该属性只对MyBatis3有效,如果true就会使用构造方法入参,如果false就会使用setter方式。默认为false。 -->
            <property name="constructorBased" value="true" />
             <!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] -->  
            <property name="enableSubPackages" value="false" />
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->  
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 生成mapxml文件 -->  
        <sqlMapGenerator targetPackage="${package.mapper}" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="${package.mapper}" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!--   选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
                    选择的table会生成一下文件:
                    1,SQL map文件
                    2,生成一个主键类;
                    3,除了BLOB和主键的其他字段的类;
                    4,包含BLOB的类;
                    5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选;
                    6,Mapper接口(可选)

                    tableName(必要):要生成对象的表名;
                    注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会
                        根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
                        1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询;
                        2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找;
                        3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找;
                        4,否则,使用指定的大小写格式查询;
                    另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名;
                    这个时候,请设置delimitIdentifiers="true"即可保留大小写格式;

                    可选:
                    1,schema:数据库的schema;
                    2,catalog:数据库的catalog;
                    3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
                    4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面;
                    5,enableInsert(默认true):指定是否生成insert语句;
                    6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
                    7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句;
                    8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
                    9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
                    10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句;
                    11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询);
                    12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性);
                    13,modelType:参考context元素的defaultModelType,相当于覆盖;
                    14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
                    15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性

                    注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写;
         -->

        <table tableName="${tableName}" 
            enableCountByExample="false" 
            enableUpdateByExample="false"
            enableDeleteByExample="false" 
            enableSelectByExample="false"
            selectByExampleQueryId="false">
            <!-- 参考 javaModelGenerator 的 constructorBased属性-->
            <property name="constructorBased" value="true" />
            <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
            <property name="useActualColumnNames" value="false" />
            <!-- 默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema; -->
            <property name="ignoreQualifiersAtRuntime" value="false" />
            <!-- 参考 javaModelGenerator 的 immutable 属性 -->
            <!-- <property name="immutable" value="false"/> -->
        </table>
    </context>
</generatorConfiguration>

对于generatorConfig.xml文件中引入的 application.properties文件,里面主要是数据库连接信息和生成的文件的目录信息,application.properties文件配置如下:

jdbc.url=jdbc:mysql:///test?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root

package.entity=com.solin.autoGenerate.entity
package.mapper=com.solin.autoGenerate.mapper
#指定要生成代码的表名,如果tableName等于%,则生成全部表的代码
tableName=user

以上文件配置好了之后,在项目上点击右键,如图:

在点击Run Configurations以后,会弹出对话框,在对话框上找到Maven Build,然后右键并且点击new,如下图:

在新出现的界面上填写Name,Base directory,Goals这三个地方,其中Name可以随便写,Base directory是你的工程的路径,Goals这个地方不用变,照着图写,这个是maven插件的命令。至于Maven  Runtime下拉框可以不选,也可以选择自己安装在eclipse外面的那个。

点击Apply,在点击 Run,稍等一会,你可以看到generate执行成功了,如图:

刷新项目,可以看到生成的文件,如图:

最后附上完整demo:http://download.csdn.net/download/qq_32786873/10022351

第五种:通过eclipse mybatis generater代码生成插件自动生成代码

详细说明见:http://blog.csdn.net/qq_32786873/article/details/78226513

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器