使用MyBatis逆向工具MyBatis GeneratorDao生成Model、Mapper、Mapping

源码点这里官方介绍点这里

一、使用Maven插件的方式

1. 新建一个项目,导入pom。

<?xml version="1.0" encoding="UTF-8"?>
<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.freech</groupId>
    <artifactId>mybatis-generator</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-maven-plugin -->
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. 编写数据源配置文件datasource.properties。

jdbc.driverLocation=D:/maven/repository/mysql/mysql-connector-java/5.1.44/mysql-connector-java-5.1.44.jar
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis-generator-test?characterEncoding=utf8
jdbc.username=root
jdbc.password=

3. 编写MBG配置文件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="datasource.properties"></properties>

    <!-- 数据库驱动的jdbc驱动jar包的位置 -->
    <classPathEntry location="${jdbc.driverLocation}"/>

    <!-- context 是逆向工程的主要配置信息 -->
    <!-- id:起个名字 -->
    <!-- targetRuntime:设置生成的文件适用于那个 mybatis 版本 -->
    <context id="mysql" targetRuntime="MyBatis3">
        <!-- 生成的Java文件的编码-->
        <property name="javaFileEncoding" value="UTF-8"/>

        <!--无必须属性。Comment Generator用于为MyBatis Generator(MBG)生成的各种元素生成注释(Java字段,Java方法,XML元素等)。默认的Comment Generator将JavaDoc注释添加到所有生成的Java元素,以在Eclipse插件中启用Java合并功能。此外,还会为每个生成的XML元素添加注释。-->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

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

        <!--无必须属性。<javaTypeResolver>元素用于定义Java类型解析器的属性。Java Type Resolver用于根据数据库列信息计算Java类型。如果可能的话,默认的Java Type Resolver尝试通过替换Integral类型(Long,Integer,Short等)来尝试使JDBC DECIMAL和NUMERIC类型更容易使用。如果不希望出现这种情况,请将属性“forceBigDecimals”设置为“true”。如果您想要与默认行为不同的行为,也可以替换自己的实现。-->
        <javaTypeResolver>
            <!-- 此属性用于指定MyBatis Generator是否应强制对DECIMAL和NUMERIC字段使用java.math.BigDecimal,而不是在可能时替换整数类型。-->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- <javaModelGenerator>元素用于定义Java模型生成器的属性。 -->
        <!-- targetProject 这用于为生成的对象指定目标项目。 -->
        <!-- targetPackage 这是生成的类将被放置的包。 -->
        <javaModelGenerator targetPackage="com.freech.model" targetProject=".\src\main\java">
            <!-- 此属性仅适用于MyBatis3,iBATIS2将被忽略。此属性用于选择MyBatis Generator是否将为接受类中每个字段的值的类生成构造函数。 -->
            <property name="constructorBased" value="false"/>
            <!-- 此属性用于选择MyBatis Generator是否将根据内省表的目录和架构为对象生成不同的Java包。
                例如,假设模式MYSCHMA中的表为MYTABLE。还假设targetPackage属性设置为“com.mycompany”。
                如果此属性为true,则表的生成对象将放在包“com.mycompany.myschema”中。
                如果属性为false,则生成的对象将放在“com.mycompany”架构中。默认值为false。-->
            <property name="enableSubPackages" value="true"/>

            <!-- 建立modal对象是否不可改变 即生成的modal对象不会有setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
            <!-- 设置一个根对象,如果设置了这个根对象,那么生成的keyClass或者recordClass会继承这个类;在Table的rootClass属性中可以覆盖该选项;
                提示:如果在key class或者record class中有root class相同的属性,就不会重新生成这些属性了:属性名相同,类型相同,有相同的getter/setter;-->
            <property name="rootClass" value="com.freech.base.BaseModel"/>
            <!-- 是否清理从数据库中查询出的字符串左右两边的空白字符 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- targetPackage 和 targetProject:生成的 mapper 文件的包和位置 -->
        <sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">
            <!-- 针对数据库的一个配置,是否把 schema 作为字包名 -->
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- <javaClientGenerator>元素用于定义Java客户端生成器的属性。Java客户端生成器构建Java接口和类,
        允许轻松使用生成的Java模型和XML映射文件。对于iBATIS2目标环境,这些生成的对象采用DAO接口和实现类的形式。
        对于MyBatis,生成的对象采用映射器接口的形式。此元素是<context>元素的可选子元素。如果未指定此元素,
        则MyBatis Generator(MBG)将不会生成Java客户端接口和类。
        1. ANNOTATEDMAPPER	生成的对象将是MyBatis 3.x映射器基础结构的Java接口。接口将基于注释和MyBatis 3.x SqlProviders。不会生成XML映射器文件。
            ANNOTATEDMAPPER需要MyBatis 3.0.4或更高版本。
        2.  MIXEDMAPPER	生成的对象将是MyBatis 3.x映射器基础结构的Java接口。接口将基于注释和XML的混合。将使用注释将在简单注释工作的地方使用。此客户端不会生成和Sql Provider,因此所有复杂的动态SQL都将以XML格式生成。
            MIXEDMAPPER需要MyBatis 3.0.4或更高版本。
        3. XMLMAPPER	生成的对象将是MyBatis 3.x映射器基础结构的Java接口。接口将依赖于生成的XML映射器文件。
        -->
        <!-- targetPackage 和 targetProject:生成的 interface 文件的包和位置 -->
        <!-- rootInterface 此属性可用于为所有生成的接口对象指定超级接口。可以通过在Table配置上指定rootInterface属性来覆盖此值。
                要点: MBG不验证接口是否存在,或者是否是有效的Java接口。
                如果指定,则此属性的值应为完全限定的接口名称(如com.mycompany.MyRootInterface)。 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.freech.mapper" targetProject=".\src\main\java">
            <!-- 针对 oracle 数据库的一个配置,是否把 schema 作为字包名 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!-- 必须属性:tableName。
            enableInsert	表示是否应生成插入语句。
            默认值为true。

            enableSelectByPrimaryKey	表示是否应生成select by primary key语句。无论此设置如何,如果表没有主键,则不会生成语句。
            默认值为true。

            enableSelectByExample	表示是否应生成select by example语句。此语句允许在运行时生成许多不同的动态查询。
            默认值为true。

            enableUpdateByPrimaryKey	表示是否应生成主键语句更新。无论此设置如何,如果表没有主键,则不会生成语句。
            默认值为true。

            enableDeleteByPrimaryKey	表示是否应生成主键语句删除。无论此设置如何,如果表没有主键,则不会生成语句。
            默认值为true。

            enableDeleteByExample	表示是否应生成按示例删除语句。此语句允许在运行时生成许多不同的动态删除。
            默认值为true。

            enableCountByExample	表示是否应生成按语句计数的语句。此语句将返回表中与示例匹配的行数。
            默认值为true。

            enableUpdateByExample	表示是否应生成示例语句的更新。此语句将更新表中与示例匹配的行。如果为true,则还将生成示例“selective”语句的更新。“selective”语句仅更新record参数中的相应值为非null的列。
            默认值为true。

            selectByPrimaryKeyQueryId	此值将以此形式添加到select by primary key语句的选择列表中:“'<value>'作为QUERYID”。这对于在运行时识别DBA跟踪工具中的查询非常有用。如果使用这样的值,则应为MBG生成的每个不同查询指定唯一ID。
            selectByExampleQueryId	此值将以此形式添加到select by example语句的选择列表中:“'<value>'作为QUERYID”。这对于在运行时识别DBA跟踪工具中的查询非常有用。如果使用这样的值,则应为MBG生成的每个不同查询指定唯一ID。
        -->
        <table tableName="u_user" domainObjectName="User"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
        <table tableName="u_role" domainObjectName="Role"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>
  1. 使用插件一键生成代码。
    在这里插入图片描述

二、使用代码的方式生成

编写测试类,右键运行即可

public class GeneratorTest {
    @Test
    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指定 逆向工程配置文件
        File configFile = new File("src\\main\\resources\\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);

    }
}
posted @ 2018-11-20 10:34  _chenyl  阅读(85)  评论(0编辑  收藏  举报