Mybatis generator的简单使用

示例环境:Eclipse+Springboot+Mybatis+Mysql

一,pom.xml引入相关依赖

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
         <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>

二,测试数据库表

CREATE TABLE `m_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `sex` varchar(5) DEFAULT NULL,
  `address` varchar(100) DEFAULT NULL,
  `birthday` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


CREATE TABLE `student` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
  `age` tinyint(3) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

三,数据库连接配置(application.properties)

spring.datasource.driverClassName= com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisdemo?characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username= root
spring.datasource.password= root

需要说明的是,在springboot中可以有两种类型的配置文件,一种是.properties,另一种是.yml。.properties的优先级高于yml。在加载过程先加载.yml,后加载.properties,如果里面有相同的属性配置,则后者覆盖前者。

四,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>

    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除所有自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver" 
                        connectionURL="jdbc:mysql://localhost:3306/mybatisdemo?serverTimezone=UTC" 
                        userId="root" 
                        password="root">      
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--  entity存放位置 -->
        <javaModelGenerator targetPackage="com.hsw.sps.entity" targetProject="SST/src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

         <!--  mapper存放位置 -->
        <sqlMapGenerator targetPackage="com.hsw.sps.dao" targetProject="SST/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- xml文件存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hsw.sps.dao" targetProject="SST/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

		<table tableName="m_user"  domainObjectName="User"
		           enableCountByExample="false"
		           enableUpdateByExample="false"
		           enableDeleteByExample="false"
		           enableSelectByExample="false"
		           selectByExampleQueryId="false"/>

    </context>
</generatorConfiguration>

五,eclipse安装Mybatis generator插件

六,执行generatorConfig.xml,右键选择 Run as > Run Mybatis Generator

七,运行结果

MyBatis Generator Started...
  Buildfile: H:\workspace\.metadata\.plugins\org.mybatis.generator.eclipse.ui\.generatedAntScripts\SST-generatorConfig.xml.xml
  17:06:27.322 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.eclipse.ui.ant.logging.AntLogFactory - Logging initialized using 'org.mybatis.generator.eclipse.ui.ant.logging.slf4j.Slf4jLoggingLogFactory@66aa684d' adapter.
  17:06:27.337 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.logging.LogFactory - Logging initialized using 'org.mybatis.generator.eclipse.ui.ant.logging.AntLogFactory@2e2bf5b8' adapter.
  Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
  17:06:27.772 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Retrieving column information for table "m_user"
  17:06:27.866 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "id", data type 4, in table "mybatisdemo..m_user"
  17:06:27.866 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "username", data type 12, in table "mybatisdemo..m_user"
  17:06:27.867 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "sex", data type 12, in table "mybatisdemo..m_user"
  17:06:27.867 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "address", data type 12, in table "mybatisdemo..m_user"
  17:06:27.867 [Worker-61: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "birthday", data type 93, in table "mybatisdemo..m_user"
  BUILD SUCCESSFUL
MyBatis Generator Finished

ps:这里提示com.mysql.jdbc.Driver已经弃用,应该使用com.mysql.cj.jdbc.Driver

执行成功后,可以看到相关表的entity,mapper,xml 已经创建,如果运行成功相关的包却没有创建的话,项目刷新就可以看见了,如果此时再次运行mybatis genrtator的话,会不断往已经创建的文件内追加内容,也就是说,如果想要再次生成的话,需要把相关文件删除之后,重新生成。

八,刚才的generatorConfig.xml内,只配置了user表的相关映射,所以生成了user表的相关文件,那还有一个student表,需要重新写一遍student表的配置吗?那如果数据库表内有几百张表,难道都需要手动定义吗?答案是否定的,mybatis generator可以自动生成库下的所有表,关键配置如下

<table schema="mybatisdemo"  tableName="%"  
                   enableCountByExample="false"  
                   enableUpdateByExample="false"   
                   enableDeleteByExample="false" 
                   enableSelectByExample="false"  
                   selectByExampleQueryId="false"/>

全部的配置文件

<?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>

    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除所有自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" 
                        connectionURL="jdbc:mysql://localhost:3306/mybatisdemo?serverTimezone=UTC" 
                        userId="root" 
                        password="root">
           <property name="nullCatalogMeansCurrent" value="true"/> 
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--  entity存放位置 -->
        <javaModelGenerator targetPackage="com.hsw.sps.entity" targetProject="SST/src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

         <!--  mapper存放位置 -->
        <sqlMapGenerator targetPackage="com.hsw.sps.dao" targetProject="SST/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- xml文件存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hsw.sps.dao" targetProject="SST/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

		 <!--<table tableName="m_user"  domainObjectName="User"
		            enableCountByExample="false"
		            enableUpdateByExample="false"
		            enableDeleteByExample="false"
		            enableSelectByExample="false"
		            selectByExampleQueryId="false"/>-->
          
            <table schema="mybatisdemo"  tableName="%"  
                   enableCountByExample="false"  
                   enableUpdateByExample="false"   
                   enableDeleteByExample="false" 
                   enableSelectByExample="false"  
                   selectByExampleQueryId="false"/>  
    </context>
</generatorConfiguration>

将刚才反向生成的文件删除之后,再次运行,得到如下结果

MyBatis Generator Started...
  Buildfile: H:\workspace\.metadata\.plugins\org.mybatis.generator.eclipse.ui\.generatedAntScripts\SST-generatorConfig.xml.xml
  18:28:25.319 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.eclipse.ui.ant.logging.AntLogFactory - Logging initialized using 'org.mybatis.generator.eclipse.ui.ant.logging.slf4j.Slf4jLoggingLogFactory@6dadd05b' adapter.
  18:28:25.333 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.logging.LogFactory - Logging initialized using 'org.mybatis.generator.eclipse.ui.ant.logging.AntLogFactory@49970f30' adapter.
  18:28:25.723 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Retrieving column information for table "mybatisdemo.%"
  18:28:25.796 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "id", data type 4, in table "mybatisdemo..m_user"
  18:28:25.796 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "username", data type 12, in table "mybatisdemo..m_user"
  18:28:25.796 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "sex", data type 12, in table "mybatisdemo..m_user"
  18:28:25.796 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "address", data type 12, in table "mybatisdemo..m_user"
  18:28:25.796 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "birthday", data type 93, in table "mybatisdemo..m_user"
  18:28:25.797 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "id", data type 4, in table "mybatisdemo..student"
  18:28:25.797 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "name", data type 12, in table "mybatisdemo..student"
  18:28:25.797 [Worker-10: Launching SST-generatorConfig.xml] DEBUG org.mybatis.generator.internal.db.DatabaseIntrospector - Found column "age", data type -6, in table "mybatisdemo..student"
  BUILD SUCCESSFUL
MyBatis Generator Finished

可以看到,mybatis generator已经自动扫描了当前数据库下的所有表,并反向生成了相关文件。