• 使用maven工程实现Mybatis自动生成Mapper文件


    本文档为学习记录,参考博文:
    https://www.cnblogs.com/handsomeye/p/6268513.html
    https://www.cnblogs.com/maanshancss/p/6027999.html

    实现步骤:

    1)新建Maven工程

    新建一个Maven工程,专用于进行生成代码

    2)POM文件添加Mybatis generator依赖

    dependencies中添加:

    1 <dependency>
    2     <groupId>org.mybatis.generator</groupId>
    3     <artifactId>mybatis-generator-core</artifactId>
    4     <version>1.3.2</version>
    5 </dependency>

    在build的plugins中添加:

     1 <plugin>
     2     <groupId>org.mybatis.generator</groupId>
     3     <artifactId>mybatis-generator-maven-plugin</artifactId>
     4     <version>1.3.2</version>
     5     <configuration>
     6        <!-- mybatis用于生成代码的配置文件 -->
     7       <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
     8         <verbose>true</verbose>
     9         <overwrite>true</overwrite>
    10     </configuration>
    11 </plugin>

    3.配置generatorConfig.xml

    如下为一份有效配置:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE generatorConfiguration
     3  PUBLIC " -//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
     4  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
     5 <generatorConfiguration>
     6     <classPathEntry
     7             location="/Users/yehaixiao/Maven/mysql/mysql-connector-java/5.1.30/mysql-connector-java.jar"/>
     8     <context id="my" targetRuntime="MyBatis3">
     9     
    10         <!-- 生成的Java文件的编码 -->
    11         <property name="javaFileEncoding" value="UTF-8"/>
    12         <!-- 格式化java代码 -->
    13         <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
    14         <!-- 格式化XML代码 -->
    15         <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
    16 
    17         <commentGenerator>
    18             <property name="suppressDate" value="false"/>
    19             <property name="suppressAllComments" value="true"/>
    20         </commentGenerator>
    21         
    22      <!-- mysql数据库连接 --> 
    23         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
    24                         connectionURL="jdbc:mysql://127.0.0.1:3306/test" userId="root"
    25                         password="******"/>
    26 
    27      <!-- 生成model实体类文件位置 -->
    28         <javaModelGenerator targetPackage="com.ssmgen.demo.model"
    29                             targetProject="/Users/yehaixiao/asiainfo/ssm-demo/src/main/java">
    30             <property name="enableSubPackages" value="true"/>
    31             <property name="trimStrings" value="true"/>
    32         </javaModelGenerator>
    33 
    34     <!-- 生成mapper.xml配置文件位置 -->
    35         <sqlMapGenerator targetPackage="com.ssmgen.demo.mapper"
    36                          targetProject="/Users/yehaixiao/asiainfo/ssm-demo/src/main/java">
    37             <property name="enableSubPackages" value="true"/>
    38         </sqlMapGenerator>
    39 
    40         <!-- 生成mapper接口文件位置 -->
    41         <javaClientGenerator targetPackage="com.ssmgen.demo.mapper"
    42                              targetProject="/Users/yehaixiao/asiainfo/ssm-demo/src/main/java" type="XMLMAPPER">
    43             <property name="enableSubPackages" value="true"/>
    44         </javaClientGenerator>
    45         
    46      <!-- 需要生成的实体类对应的表名,多个实体类复制多份该配置即可 -->
    47         <table tableName="TEST1" domainObjectName="Test"
    48                enableCountByExample="false" enableUpdateByExample="false"
    49                enableDeleteByExample="false" enableSelectByExample="false"
    50                selectByExampleQueryId="false">
    51         </table>
    52     </context>
    53 </generatorConfiguration>

    配置说明:

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <!DOCTYPE generatorConfiguration
      3   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
      4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
      5 <!-- 配置生成器 -->
      6 <generatorConfiguration>
      7 <!-- 可以用于加载配置项或者配置文件,在整个配置文件中就可以使用${propertyKey}的方式来引用配置项
      8     resource:配置资源加载地址,使用resource,MBG从classpath开始找,比如com/myproject/generatorConfig.properties        
      9     url:配置资源加载地质,使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties.
     10     注意,两个属性只能选址一个;
     11 
     12     另外,如果使用了mybatis-generator-maven-plugin,那么在pom.xml中定义的properties都可以直接在generatorConfig.xml中使用
     13 <properties resource="" url="" />
     14  -->
     15 
     16  <!-- 在MBG工作的时候,需要额外加载的依赖包
     17      location属性指明加载jar/zip包的全路径
     18 <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />
     19   -->
     20 
     21 <!-- 
     22     context:生成一组对象的环境 
     23     id:必选,上下文id,用于在生成错误时提示
     24     defaultModelType:指定生成对象的样式
     25     targetRuntime:
     26         1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
     27         2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
     28     introspectedColumnImpl:类全限定名,用于扩展MBG
     29 -->
     30 <context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >
     31 
     32     <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
     33         一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖
     34      -->
     35     <property name="autoDelimitKeywords" value="false"/>
     36     <!-- 生成的Java文件的编码 -->
     37     <property name="javaFileEncoding" value="UTF-8"/>
     38     <!-- 格式化java代码 -->
     39     <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
     40     <!-- 格式化XML代码 -->
     41     <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
     42 
     43     <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
     44     <property name="beginningDelimiter" value="`"/>
     45     <property name="endingDelimiter" value="`"/>
     46 
     47     <!-- 必须要有的,使用这个配置链接数据库
     48         @TODO:是否可以扩展
     49      -->
     50     <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql:///pss" userId="root" password="admin">
     51         <!-- 这里面可以设置property属性,每一个property属性都设置到配置的Driver上 -->
     52     </jdbcConnection>
     53 
     54     <!-- java类型处理器 
     55         用于处理DB中的类型到Java中的类型,默认使用JavaTypeResolverDefaultImpl;
     56         注意一点,默认会先尝试使用Integer,Long,Short等来对应DECIMAL和 NUMERIC数据类型; 
     57     -->
     58     <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
     59         <!-- 
     60             true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型
     61             false:默认,
     62                 scale>0;length>18:使用BigDecimal;
     63                 scale=0;length[10,18]:使用Long;
     64                 scale=0;length[5,9]:使用Integer;
     65                 scale=0;length<5:使用Short;
     66          -->
     67         <property name="forceBigDecimals" value="false"/>
     68     </javaTypeResolver>
     69 
     70 
     71     <!-- java模型创建器,是必须要的元素
     72         负责:1,key类(见context的defaultModelType);2,java类;3,查询类
     73         targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制;
     74         targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录
     75      -->
     76     <javaModelGenerator targetPackage="com._520it.mybatis.domain" targetProject="src/main/java">
     77         <!--  for MyBatis3/MyBatis3Simple
     78             自动为每一个生成的类创建一个构造方法,构造方法包含了所有的field;而不是使用setter;
     79          -->
     80         <property name="constructorBased" value="false"/>
     81 
     82         <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
     83         <property name="enableSubPackages" value="true"/>
     84 
     85         <!-- for MyBatis3 / MyBatis3Simple
     86             是否创建一个不可变的类,如果为true,
     87             那么MBG会创建一个没有setter方法的类,取而代之的是类似constructorBased的类
     88          -->
     89         <property name="immutable" value="false"/>
     90 
     91         <!-- 设置一个根对象,
     92             如果设置了这个根对象,那么生成的keyClass或者recordClass会继承这个类;在Table的rootClass属性中可以覆盖该选项
     93             注意:如果在key class或者record class中有root class相同的属性,MBG就不会重新生成这些属性了,包括:
     94                 1,属性名相同,类型相同,有相同的getter/setter方法;
     95          -->
     96         <property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/>
     97 
     98         <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
     99         <property name="trimStrings" value="true"/>
    100     </javaModelGenerator>
    101 
    102 
    103     <!-- 生成SQL map的XML文件生成器,
    104         注意,在Mybatis3之后,我们可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),
    105             或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的话,这个元素就必须配置
    106         targetPackage/targetProject:同javaModelGenerator
    107      -->
    108     <sqlMapGenerator targetPackage="com._520it.mybatis.mapper" targetProject="src/main/resources">
    109         <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
    110         <property name="enableSubPackages" value="true"/>
    111     </sqlMapGenerator>
    112 
    113 
    114     <!-- 对于mybatis来说,即生成Mapper接口,注意,如果没有配置该元素,那么默认不会生成Mapper接口 
    115         targetPackage/targetProject:同javaModelGenerator
    116         type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
    117             1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML;
    118             2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中;
    119             3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
    120         注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
    121     -->
    122     <javaClientGenerator targetPackage="com._520it.mybatis.mapper" type="ANNOTATEDMAPPER" targetProject="src/main/java">
    123         <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
    124         <property name="enableSubPackages" value="true"/>
    125 
    126         <!-- 可以为所有生成的接口添加一个父接口,但是MBG只负责生成,不负责检查
    127         <property name="rootInterface" value=""/>
    128          -->
    129     </javaClientGenerator>
    130 
    131     <!-- 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
    132         选择的table会生成一下文件:
    133         1,SQL map文件
    134         2,生成一个主键类;
    135         3,除了BLOB和主键的其他字段的类;
    136         4,包含BLOB的类;
    137         5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选;
    138         6,Mapper接口(可选)
    139 
    140         tableName(必要):要生成对象的表名;
    141         注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会
    142             根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
    143             1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询;
    144             2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找;
    145             3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找;
    146             4,否则,使用指定的大小写格式查询;
    147         另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名;
    148         这个时候,请设置delimitIdentifiers="true"即可保留大小写格式;
    149 
    150         可选:
    151         1,schema:数据库的schema;
    152         2,catalog:数据库的catalog;
    153         3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
    154         4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面;
    155         5,enableInsert(默认true):指定是否生成insert语句;
    156         6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
    157         7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句;
    158         8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
    159         9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
    160         10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句;
    161         11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询);
    162         12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性);
    163         13,modelType:参考context元素的defaultModelType,相当于覆盖;
    164         14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
    165         15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性
    166 
    167         注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写;
    168      -->
    169     <table tableName="userinfo" >
    170 
    171         <!-- 参考 javaModelGenerator 的 constructorBased属性-->
    172         <property name="constructorBased" value="false"/>
    173 
    174         <!-- 默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema; -->
    175         <property name="ignoreQualifiersAtRuntime" value="false"/>
    176 
    177         <!-- 参考 javaModelGenerator 的 immutable 属性 -->
    178         <property name="immutable" value="false"/>
    179 
    180         <!-- 指定是否只生成domain类,如果设置为true,只生成domain类,如果还配置了sqlMapGenerator,那么在mapper XML文件中,只生成resultMap元素 -->
    181         <property name="modelOnly" value="false"/>
    182 
    183         <!-- 参考 javaModelGenerator 的 rootClass 属性 
    184         <property name="rootClass" value=""/>
    185          -->
    186 
    187         <!-- 参考javaClientGenerator 的  rootInterface 属性
    188         <property name="rootInterface" value=""/>
    189         -->
    190 
    191         <!-- 如果设置了runtimeCatalog,那么在生成的SQL中,使用该指定的catalog,而不是table元素上的catalog 
    192         <property name="runtimeCatalog" value=""/>
    193         -->
    194 
    195         <!-- 如果设置了runtimeSchema,那么在生成的SQL中,使用该指定的schema,而不是table元素上的schema 
    196         <property name="runtimeSchema" value=""/>
    197         -->
    198 
    199         <!-- 如果设置了runtimeTableName,那么在生成的SQL中,使用该指定的tablename,而不是table元素上的tablename 
    200         <property name="runtimeTableName" value=""/>
    201         -->
    202 
    203         <!-- 注意,该属性只针对MyBatis3Simple有用;
    204             如果选择的runtime是MyBatis3Simple,那么会生成一个SelectAll方法,如果指定了selectAllOrderByClause,那么会在该SQL中添加指定的这个order条件;
    205          -->
    206         <property name="selectAllOrderByClause" value="age desc,username asc"/>
    207 
    208         <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
    209         <property name="useActualColumnNames" value="false"/>
    210 
    211 
    212         <!-- generatedKey用于生成生成主键的方法,
    213             如果设置了该元素,MBG会在生成的<insert>元素中生成一条正确的<selectKey>元素,该元素可选
    214             column:主键的列名;
    215             sqlStatement:要生成的selectKey语句,有以下可选项:
    216                 Cloudscape:相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL()
    217                 DB2       :相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL()
    218                 DB2_MF    :相当于selectKey的SQL为:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
    219                 Derby      :相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL()
    220                 HSQLDB      :相当于selectKey的SQL为:CALL IDENTITY()
    221                 Informix  :相当于selectKey的SQL为:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
    222                 MySql      :相当于selectKey的SQL为:SELECT LAST_INSERT_ID()
    223                 SqlServer :相当于selectKey的SQL为:SELECT SCOPE_IDENTITY()
    224                 SYBASE      :相当于selectKey的SQL为:SELECT @@IDENTITY
    225                 JDBC      :相当于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty属性
    226         <generatedKey column="" sqlStatement=""/>
    227          -->
    228 
    229         <!-- 
    230             该元素会在根据表中列名计算对象属性名之前先重命名列名,非常适合用于表中的列都有公用的前缀字符串的时候,
    231             比如列名为:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等;
    232             那么就可以设置searchString为"^CUST_",并使用空白替换,那么生成的Customer对象中的属性名称就不是
    233             custId,custName等,而是先被替换为ID,NAME,EMAIL,然后变成属性:id,name,email;
    234 
    235             注意,MBG是使用java.util.regex.Matcher.replaceAll来替换searchString和replaceString的,
    236             如果使用了columnOverride元素,该属性无效;
    237 
    238         <columnRenamingRule searchString="" replaceString=""/>
    239          -->
    240 
    241 
    242          <!-- 用来修改表中某个列的属性,MBG会使用修改后的列来生成domain的属性;
    243              column:要重新设置的列名;
    244              注意,一个table元素中可以有多个columnOverride元素哈~
    245           -->
    246          <columnOverride column="username">
    247              <!-- 使用property属性来指定列要生成的属性名称 -->
    248              <property name="property" value="userName"/>
    249 
    250              <!-- javaType用于指定生成的domain的属性类型,使用类型的全限定名
    251              <property name="javaType" value=""/>
    252               -->
    253 
    254              <!-- jdbcType用于指定该列的JDBC类型 
    255              <property name="jdbcType" value=""/>
    256               -->
    257 
    258              <!-- typeHandler 用于指定该列使用到的TypeHandler,如果要指定,配置类型处理器的全限定名
    259                  注意,mybatis中,不会生成到mybatis-config.xml中的typeHandler
    260                  只会生成类似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的参数描述
    261              <property name="jdbcType" value=""/>
    262              -->
    263 
    264              <!-- 参考table元素的delimitAllColumns配置,默认为false
    265              <property name="delimitedColumnName" value=""/>
    266               -->
    267          </columnOverride>
    268 
    269          <!-- ignoreColumn设置一个MGB忽略的列,如果设置了改列,那么在生成的domain中,生成的SQL中,都不会有该列出现 
    270              column:指定要忽略的列的名字;
    271              delimitedColumnName:参考table元素的delimitAllColumns配置,默认为false
    272 
    273              注意,一个table元素中可以有多个ignoreColumn元素
    274          <ignoreColumn column="deptId" delimitedColumnName=""/>
    275          -->
    276     </table>
    277 
    278 </context>

    4)执行生成

    到此为止,所有的配置已完毕,如果在ecplise中使用,则右击工程,maven build,添加命令mybatis-generator:generate,代码生成完毕!

    生成带字段注释的

    按照上面的生成,pojo类中没有关于字段的注释,参照 https://www.jb51.net/article/148070.htm 一文的讲解,重新修改

    1)配置pom文件,只需要引入自动生成的jar包,不在配置插件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     4     <modelVersion>4.0.0</modelVersion>
     5     <parent>
     6         <groupId>org.springframework.boot</groupId>
     7         <artifactId>spring-boot-starter-parent</artifactId>
     8         <version>2.1.5.RELEASE</version>
     9         <relativePath/> <!-- lookup parent from repository -->
    10     </parent>
    11     <groupId>com.swyx</groupId>
    12     <artifactId>swyx_form_api</artifactId>
    13     <version>0.0.1-SNAPSHOT</version>
    14     <name>swyx_form_api</name>
    15     <description>Demo project for Spring Boot</description>
    16 
    17     <properties>
    18         <java.version>1.8</java.version>
    19     </properties>
    20 
    21     <dependencies>
    22         <dependency>
    23             <groupId>org.springframework.boot</groupId>
    24             <artifactId>spring-boot-starter-web</artifactId>
    25         </dependency>
    26         <dependency>
    27             <groupId>org.mybatis.spring.boot</groupId>
    28             <artifactId>mybatis-spring-boot-starter</artifactId>
    29             <version>2.0.1</version>
    30         </dependency>
    31         <dependency>
    32             <groupId>org.springframework.boot</groupId>
    33             <artifactId>spring-boot-starter-test</artifactId>
    34             <scope>test</scope>
    35         </dependency>
    36 
    37         <!-- mysql -->
    38         <dependency>
    39             <groupId>mysql</groupId>
    40             <artifactId>mysql-connector-java</artifactId>
    41             <scope>runtime</scope>
    42         </dependency>
    43         <dependency>
    44             <groupId>org.mybatis.generator</groupId>
    45             <artifactId>mybatis-generator-core</artifactId>
    46             <version>1.3.7</version>
    47         </dependency>
    48         
    49     </dependencies>
    50 
    51     <build>
    52         <plugins>
    53             <plugin>
    54                 <groupId>org.springframework.boot</groupId>
    55                 <artifactId>spring-boot-maven-plugin</artifactId>
    56             </plugin>
    57         </plugins>
    58     </build>
    59 </project>

    2)编写自动生成工具类

      1 package com.swyx.form.api;
      2 
      3 import org.mybatis.generator.api.CommentGenerator;
      4 import org.mybatis.generator.api.IntrospectedColumn;
      5 import org.mybatis.generator.api.IntrospectedTable;
      6 import org.mybatis.generator.api.dom.java.*;
      7 import org.mybatis.generator.api.dom.xml.XmlElement;
      8 import java.util.Properties;
      9 import java.util.Set;
     10 import org.mybatis.generator.api.dom.java.Field;
     11 import org.mybatis.generator.api.dom.java.TopLevelClass;
     12 import java.text.SimpleDateFormat;
     13 import java.util.Date;
     14 
     15 public class MySQLCommentGenerator extends EmptyCommentGenerator {
     16 
     17     private Properties properties;
     18 
     19     public MySQLCommentGenerator() {
     20         properties = new Properties();
     21     }
     22 
     23     @Override
     24     public void addConfigurationProperties(Properties properties) {
     25         // 获取自定义的 properties
     26         this.properties.putAll(properties);
     27     }
     28 
     29     @Override
     30     public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
     31         String author = properties.getProperty("author");
     32         String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd");
     33         SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
     34 
     35         // 获取表注释
     36         String remarks = introspectedTable.getRemarks();
     37 
     38         topLevelClass.addJavaDocLine("/**");
     39         topLevelClass.addJavaDocLine(" * " + remarks);
     40         topLevelClass.addJavaDocLine(" *");
     41         topLevelClass.addJavaDocLine(" * @author " + author);
     42         topLevelClass.addJavaDocLine(" * @date   " + dateFormatter.format(new Date()));
     43         topLevelClass.addJavaDocLine(" */");
     44     }
     45 
     46     @Override
     47     public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
     48         // 获取列注释
     49         String remarks = introspectedColumn.getRemarks();
     50         field.addJavaDocLine("/**");
     51         field.addJavaDocLine(" * " + remarks);
     52         field.addJavaDocLine(" */");
     53     }
     54 }
     55 
     56 class EmptyCommentGenerator implements CommentGenerator {
     57 
     58     @Override
     59     public void addConfigurationProperties(Properties properties) {
     60 
     61     }
     62 
     63     @Override
     64     public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
     65 
     66     }
     67 
     68     @Override
     69     public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
     70 
     71     }
     72 
     73     @Override
     74     public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
     75 
     76     }
     77 
     78     @Override
     79     public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
     80 
     81     }
     82 
     83     @Override
     84     public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean b) {
     85 
     86     }
     87 
     88     @Override
     89     public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
     90 
     91     }
     92 
     93     @Override
     94     public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
     95 
     96     }
     97 
     98     @Override
     99     public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
    100 
    101     }
    102 
    103     @Override
    104     public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
    105 
    106     }
    107 
    108     @Override
    109     public void addJavaFileComment(CompilationUnit compilationUnit) {
    110 
    111     }
    112 
    113     @Override
    114     public void addComment(XmlElement xmlElement) {
    115 
    116     }
    117 
    118     @Override
    119     public void addRootComment(XmlElement xmlElement) {
    120 
    121     }
    122 
    123     @Override
    124     public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> set) {
    125 
    126     }
    127 
    128     @Override
    129     public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> set) {
    130 
    131     }
    132 
    133     @Override
    134     public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> set) {
    135 
    136     }
    137 
    138     @Override
    139     public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> set) {
    140 
    141     }
    142 
    143     @Override
    144     public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> set) {
    145 
    146     }
    147 }
     1 package com.swyx.form.api;
     2 
     3 import org.mybatis.generator.api.MyBatisGenerator;
     4 import org.mybatis.generator.config.Configuration;
     5 import org.mybatis.generator.config.xml.ConfigurationParser;
     6 import org.mybatis.generator.internal.DefaultShellCallback;
     7 import java.io.File;
     8 import java.util.ArrayList;
     9 import java.util.List;
    10 
    11 public class MySQLGenerator {
    12 
    13     public static void main( String[] args ) throws Exception {
    14         List<String> warnings = new ArrayList<>();
    15         File configFile = new File("src/main/resources/generatorConfig.xml");
    16         ConfigurationParser cp = new ConfigurationParser(warnings);
    17         Configuration config = cp.parseConfiguration(configFile);
    18         DefaultShellCallback callback = new DefaultShellCallback(true);
    19         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    20         myBatisGenerator.generate(null);
    21     }
    22 
    23 }

    3)编写配置生成文件generatorConfig.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE generatorConfiguration PUBLIC
     3         "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
     4         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
     5         
     6 <generatorConfiguration>
     7     <classPathEntry location="E:apache-maven-3.6.0
    epositorymysqlmysql-connector-java8.0.16"/>
     8     <context id="my" targetRuntime="MyBatis3" defaultModelType="flat">  <!-- defaultModelType="flat"是为了防止联合主键生成单独的类  -->
     9         <!-- 生成的 Java 文件的编码 -->
    10         <property name="javaFileEncoding" value="UTF-8"/>
    11         <!-- 格式化 Java 代码 -->
    12         <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
    13         <!-- 格式化 XML 代码 -->
    14         <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
    15 
    16         <!-- 自定义注释生成器 -->
    17         <commentGenerator type="com.swyx.form.api.MySQLCommentGenerator">
    18             <property name="author" value="wangbaojun1992@163.com"/>
    19             <property name="dateFormat" value="yyyy/MM/dd"/>
    20         </commentGenerator>
    21 
    22         <!-- 配置数据库连接 -->
    23         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
    24             connectionURL="jdbc:mysql://localhost:3306/swyx_form?serverTimezone=UTC" 
    25             userId="root" password="wbj@1992*">
    26             <!-- 设置 useInformationSchema 属性为 true -->
    27             <property name="useInformationSchema" value="true" />
    28         </jdbcConnection>
    29 
    30         <!-- 生成实体的位置 -->
    31         <javaModelGenerator targetPackage="com.swyx.form.api.form.domain.pojo" targetProject="H:swyxcodesswyx_formswyx_form_apisrcmainjava">
    32             <property name="enableSubPackages" value="true"/>
    33         </javaModelGenerator>
    34 
    35         <!-- 生成 Mapper 接口的位置 -->
    36         <sqlMapGenerator targetPackage="com.swyx.form.api.form.domain.mapper" targetProject="H:swyxcodesswyx_formswyx_form_apisrcmainjava">
    37             <property name="enableSubPackages" value="true"/>
    38         </sqlMapGenerator>
    39 
    40         <!-- 生成 Mapper XML 的位置 -->
    41         <javaClientGenerator targetPackage="com.swyx.form.api.form.domain.mapper" type="XMLMAPPER" targetProject="H:swyxcodesswyx_formswyx_form_apisrcmainjava">
    42             <property name="enableSubPackages" value="true"/>
    43         </javaClientGenerator>
    44 
    45         <!-- 设置数据库的表名和实体类名 -->
    46         <table tableName="form_scheme" domainObjectName="FormScheme"
    47                enableCountByExample="true" enableUpdateByExample="false"
    48                enableDeleteByExample="false" enableSelectByExample="true"
    49                selectByExampleQueryId="false">
    50         </table>
    51 
    52     </context>
    53 </generatorConfiguration>

    4)执行MySQLGenerator 的main方法生成mapper

    生成后工程目录结构:

  • 相关阅读:
    php开发_图片验证码
    php开发_php环境搭建
    中序线索二叉树算法
    WPF技巧(1)异步绑定
    WPF技巧(2)绑定到附加属性
    nhibernate 抓取策略
    wpf 控件开发基础(6) 单一容器(Decorator)
    WPF技巧(3)监测属性变更
    Caliburn v2 变更启动初始化
    wpf单容器中的Chrome
  • 原文地址:https://www.cnblogs.com/ShouWangYiXin/p/10418568.html
Copyright © 2020-2023  润新知