添加mybatis的generator插件

一、Spring Boot添加generator

1、pom.xml中引入mybatis generato插件

<!-- 這段mybatis在創建Spring Boot中選擇mybatis就會自動添加了-->
<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency> 

<!-- mybatis generator 自動生成代碼插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!--指定配置文件的名稱。默認值:${basedir}/src/main/resources/generatorConfig.xml-->
                    <configurationFile>src/main/resources/generator-config/generatorConfig.xml</configurationFile>
                    <!--如果指定了該參數,如果生成的java文件存在已經同名的文件,新生成的文件會覆蓋原有的文件。
                    如果沒有指定該參數,如果存在同名的文件,MBG會給新生成的代碼文件生成一個唯一的名字(例如: MyClass.java.1, MyClass.java.2 等等)。
                    重要: 生成器一定會自動合併或覆蓋已經生成的XML文件。默認值:false-->
                    <overwrite>true</overwrite>
                    <!--如果指定該參數,執行過程會輸出到控制檯-->
                    <verbose>true</verbose>
                </configuration>
            </plugin>

2、在resource下添加generator-config文件夾,新建generatorConfig.xml、mybatis.org/dtd/mybatis-generator-config_1_0.dtd

 配置文件generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!--上面URL可能報錯,但不影響-->
<generatorConfiguration>

    <!-- 數據庫驅動:選擇你的本地硬盤上面的數據庫驅動包-->
    <classPathEntry  location="E:\apache-maven-3.3.9\repository\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar"/>

    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--數據庫鏈接URL,用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/panabit?useUnicode=true&amp;characterEncoding=utf-8" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.xpspeed.panabit.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
            <property name="constructorBased" value="false"/>
            <property name="enableSubPackages" value="true"/>
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xpspeed.panabit.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名-->
        <table tableName="user" domainObjectName="User"
               enableInsert="true"
               enableUpdateByPrimaryKey="true"
               enableSelectByPrimaryKey="true"
               enableDeleteByPrimaryKey="true"
               enableSelectByExample="false"
               enableDeleteByExample="false"
               enableCountByExample="false"
               enableUpdateByExample="false"
               delimitAllColumns="false">
            <property name="constructorBased" value="false"/>
            <property name="ignoreQualifiersAtRuntime" value="false"/>
            <property name="immutable" value="false"/>
            <property name="modelOnly" value="false"/>
            <property name="useActualColumnNames" value="false"/>
            <property name="useColumnIndexes" value="true"/>
        </table>
    </context>
</generatorConfiguration>

mybatis.org/dtd/mybatis-generator-config_1_0.dtd

<?xml version="1.0" encoding="UTF-8"?>
        <!--

               Copyright 2006-2017 the original author or authors.

               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.

        -->
        <!--
          This DTD defines the structure of the MyBatis generator configuration file.
          Configuration files should declare the DOCTYPE as follows:

          <!DOCTYPE generatorConfiguration PUBLIC
            "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

          Please see the documentation included with MyBatis generator for details on each option
          in the DTD.  You may also view documentation on-line here:

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

        -->

        <!--
          The generatorConfiguration element is the root element for configurations.
        -->
        <!ELEMENT generatorConfiguration (properties?, classPathEntry*, context+)>

        <!--
          The properties element is used to define a standard Java properties file
          that contains placeholders for use in the remainder of the configuration
          file.
        -->
        <!ELEMENT properties EMPTY>
        <!ATTLIST properties
                resource CDATA #IMPLIED
                url CDATA #IMPLIED>

        <!--
          The context element is used to describe a context for generating files, and the source
          tables.
        -->
        <!ELEMENT context (property*, plugin*, commentGenerator?, (connectionFactory | jdbcConnection), javaTypeResolver?,
                javaModelGenerator, sqlMapGenerator?, javaClientGenerator?, table+)>
        <!ATTLIST context id ID #REQUIRED
                defaultModelType CDATA #IMPLIED
                targetRuntime CDATA #IMPLIED
                introspectedColumnImpl CDATA #IMPLIED>

        <!--
          The connectionFactory element is used to describe the connection factory used
          for connecting to the database for introspection.  Either connectionFacoty
          or jdbcConnection must be specified, but not both.
        -->
        <!ELEMENT connectionFactory (property*)>
        <!ATTLIST connectionFactory
                type CDATA #IMPLIED>

        <!--
          The jdbcConnection element is used to describe the JDBC connection that the generator
          will use to introspect the database.
        -->
        <!ELEMENT jdbcConnection (property*)>
        <!ATTLIST jdbcConnection
                driverClass CDATA #REQUIRED
                connectionURL CDATA #REQUIRED
                userId CDATA #IMPLIED
                password CDATA #IMPLIED>

        <!--
          The classPathEntry element is used to add the JDBC driver to the run-time classpath.
          Repeat this element as often as needed to add elements to the classpath.
        -->
        <!ELEMENT classPathEntry EMPTY>
        <!ATTLIST classPathEntry
                location CDATA #REQUIRED>

        <!--
          The property element is used to add custom properties to many of the generator's
          configuration elements.  See each element for example properties.
          Repeat this element as often as needed to add as many properties as necessary
          to the configuration element.
        -->
        <!ELEMENT property EMPTY>
        <!ATTLIST property
                name CDATA #REQUIRED
                value CDATA #REQUIRED>

        <!--
          The plugin element is used to define a plugin.
        -->
        <!ELEMENT plugin (property*)>
        <!ATTLIST plugin
                type CDATA #REQUIRED>

        <!--
          The javaModelGenerator element is used to define properties of the Java Model Generator.
          The Java Model Generator builds primary key classes, record classes, and Query by Example
          indicator classes.
        -->
        <!ELEMENT javaModelGenerator (property*)>
        <!ATTLIST javaModelGenerator
                targetPackage CDATA #REQUIRED
                targetProject CDATA #REQUIRED>

        <!--
          The javaTypeResolver element is used to define properties of the Java Type Resolver.
          The Java Type Resolver is used to calculate Java types from database column information.
          The default Java Type Resolver attempts to make JDBC DECIMAL and NUMERIC types easier
          to use by substituting Integral types if possible (Long, Integer, Short, etc.)
        -->
        <!ELEMENT javaTypeResolver (property*)>
        <!ATTLIST javaTypeResolver
                type CDATA #IMPLIED>

        <!--
          The sqlMapGenerator element is used to define properties of the SQL Map Generator.
          The SQL Map Generator builds an XML file for each table that conforms to iBATIS'
          SqlMap DTD.
        -->
        <!ELEMENT sqlMapGenerator (property*)>
        <!ATTLIST sqlMapGenerator
                targetPackage CDATA #REQUIRED
                targetProject CDATA #REQUIRED>

        <!--
          The javaClientGenerator element is used to define properties of the Java client Generator.
          The Java Client Generator builds Java interface and implementation classes
          (as required) for each table.
          If this element is missing, then the generator will not build Java Client classes.
        -->
        <!ELEMENT javaClientGenerator (property*)>
        <!ATTLIST javaClientGenerator
                type CDATA #REQUIRED
                targetPackage CDATA #REQUIRED
                targetProject CDATA #REQUIRED
                implementationPackage CDATA #IMPLIED>

        <!--
          The table element is used to specify a database table that will be the source information
          for a set of generated objects.
        -->
        <!ELEMENT table (property*, generatedKey?, domainObjectRenamingRule?, columnRenamingRule?, (columnOverride | ignoreColumn | ignoreColumnsByRegex)*) >
        <!ATTLIST table
                catalog CDATA #IMPLIED
                schema CDATA #IMPLIED
                tableName CDATA #REQUIRED
                alias CDATA #IMPLIED
                domainObjectName CDATA #IMPLIED
                mapperName CDATA #IMPLIED
                sqlProviderName CDATA #IMPLIED
                enableInsert CDATA #IMPLIED
                enableSelectByPrimaryKey CDATA #IMPLIED
                enableSelectByExample CDATA #IMPLIED
                enableUpdateByPrimaryKey CDATA #IMPLIED
                enableDeleteByPrimaryKey CDATA #IMPLIED
                enableDeleteByExample CDATA #IMPLIED
                enableCountByExample CDATA #IMPLIED
                enableUpdateByExample CDATA #IMPLIED
                selectByPrimaryKeyQueryId CDATA #IMPLIED
                selectByExampleQueryId CDATA #IMPLIED
                modelType CDATA #IMPLIED
                escapeWildcards CDATA #IMPLIED
                delimitIdentifiers CDATA #IMPLIED
                delimitAllColumns CDATA #IMPLIED>

        <!--
          The columnOverride element is used to change certain attributes of the column
          from their default values.
        -->
        <!ELEMENT columnOverride (property*)>
        <!ATTLIST columnOverride
                column CDATA #REQUIRED
                property CDATA #IMPLIED
                javaType CDATA #IMPLIED
                jdbcType CDATA #IMPLIED
                typeHandler CDATA #IMPLIED
                isGeneratedAlways CDATA #IMPLIED
                delimitedColumnName CDATA #IMPLIED>

        <!--
          The ignoreColumn element is used to identify a column that should be ignored.
          No generated SQL will refer to the column, and no property will be generated
          for the column in the model objects.
        -->
        <!ELEMENT ignoreColumn EMPTY>
        <!ATTLIST ignoreColumn
                column CDATA #REQUIRED
                delimitedColumnName CDATA #IMPLIED>

        <!--
          The ignoreColumnsByRegex element is used to identify a column pattern that should be ignored.
          No generated SQL will refer to the column, and no property will be generated
          for the column in the model objects.
        -->
        <!ELEMENT ignoreColumnsByRegex (except*)>
        <!ATTLIST ignoreColumnsByRegex
                pattern CDATA #REQUIRED>

        <!--
          The except element is used to identify an exception to the ignoreColumnsByRegex rule.
          If a column matches the regex rule, but also matches the exception, then the
          column will be included in the generated objects.
        -->
        <!ELEMENT except EMPTY>
        <!ATTLIST except
                column CDATA #REQUIRED
                delimitedColumnName CDATA #IMPLIED>

        <!--
          The generatedKey element is used to identify a column in the table whose value
          is calculated - either from a sequence (or some other query), or as an identity column.
        -->
        <!ELEMENT generatedKey EMPTY>
        <!ATTLIST generatedKey
                column CDATA #REQUIRED
                sqlStatement CDATA #REQUIRED
                identity CDATA #IMPLIED
                type CDATA #IMPLIED>

        <!--
          The domainObjectRenamingRule element is used to specify a rule for renaming
          object domain name before the corresponding domain object name is calculated
        -->
        <!ELEMENT domainObjectRenamingRule EMPTY>
        <!ATTLIST domainObjectRenamingRule
                searchString CDATA #REQUIRED
                replaceString CDATA #IMPLIED>

        <!--
          The columnRenamingRule element is used to specify a rule for renaming
          columns before the corresponding property name is calculated
        -->
        <!ELEMENT columnRenamingRule EMPTY>
        <!ATTLIST columnRenamingRule
                searchString CDATA #REQUIRED
                replaceString CDATA #IMPLIED>

        <!--
          The commentGenerator element is used to define properties of the Comment Generator.
          The Comment Generator adds comments to generated elements.
        -->
        <!ELEMENT commentGenerator (property*)>
        <!ATTLIST commentGenerator
                type CDATA #IMPLIED>

3、運行 mybatis-generator-maven-plugin

è¿éåå¾çæè¿°

è¿éåå¾çæè¿°

添加maven命令:mybatis-generator:generate -e  

確定後點擊運行即可生成實體類,dao層類、mapper.xml文件 !!!如果多次執行,mapper.xml內方法會重複添加,啓動會報錯

è¿éåå¾çæè¿°

運行成功

è¿éåå¾çæè¿°

在springboot啓動類上添加包掃描註解 

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//配置mapper包掃描路徑,將項目中對應的mapper類的路徑加進來
@MapperScan("com.example.demo.dao")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

二、SSM框架(mybatis已經可以正常使用)添加generator

與spring boot除了Maven依賴不一樣,也不用在springboot啓動類上添加包掃描註解 ,其他配置都一樣

pom.xml中引入mybatis generato插件!!!依賴中指定了generatorConfig.xml配置文件的路徑,可根據實際修改

<plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.2</version>
          <configuration>
            <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
            <verbose>true</verbose>
            <overwrite>true</overwrite>
          </configuration>
          <executions>
            <execution>
              <id>Generate MyBatis Artifacts</id>
              <goals>
                <goal>generate</goal>
              </goals>
            </execution>
          </executions>
          <dependencies>
            <dependency>
              <groupId>org.mybatis.generator</groupId>
              <artifactId>mybatis-generator-core</artifactId>
              <version>1.3.2</version>
            </dependency>
            <!--<dependency>-->
              <!--<groupId>mysql</groupId>-->
              <!--<artifactId>mysql-connector-java</artifactId>-->
              <!--<version>5.1.40</version>-->
              <!--<scope>runtime</scope>-->
            <!--</dependency>-->
          </dependencies>
        </plugin>

剩下部分參考上面Spring boot的做法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章