谈谈mybatis-generaator的使用

    现在毕竟是ssm的统领,关于框架的设计,一般采用dao层的单独增删改查,一般不会把存在外键的处理放在dao,把复杂的逻辑放在service层,除非很有必要要在数据库层限制数据的处理之外,才会设置外键。

    针对于mybatis的xml写得可能会很烦,也很容易出错,那么我们就很有必要有工具进行处理,接下来,我们就使用基于maven的插件工具进行处理。

<plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

</plugin>

以上pom.xml文件的configurationFile配置文件的路径

<?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="generator.properties"></properties>

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

    <context id="default" targetRuntime="MyBatis3">


        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true" />
        </commentGenerator>


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



        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="org.louis.hometutor.po" targetProject="src/main/java">
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>

            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>

            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="true"/>

            <!-- 给Model添加一个父类 -->
            <property name="rootClass" value="com.foo.louis.Hello"/>

            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="org.louis.hometutor.domain" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>


        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator targetPackage="com.foo.tourist.dao" targetProject="src/main/java" type="MIXEDMAPPER">
            <property name="enableSubPackages" value=""/>
            <!--
                    定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:
                    public;
                    private;
                    protected;
                    default
                    注意:如果 targetRuntime="MyBatis3",此参数被忽略
             -->
            <property name="exampleMethodVisibility" value=""/>
            <!--
                                           方法名计数器
              Important note: this property is ignored if the target runtime is MyBatis3.
             -->
            <property name="methodNameCalculator" value=""/>

            <!--
                                                为生成的接口添加父接口
             -->
            <property name="rootInterface" value=""/>

        </javaClientGenerator>



        <table tableName="stu" schema="guihuashi">

            <!-- optional   , only for mybatis3 runtime
                 自动生成的键值(identity,或者序列值)
               如果指定此元素,MBG将会生成<selectKey>元素,然后将此元素插入到SQL Map的<insert> 元素之中
               sqlStatement 的语句将会返回新的值
               如果是一个自增主键的话,你可以使用预定义的语句,或者添加自定义的SQL语句. 预定义的值如下:
                  Cloudscape 	This will translate to: VALUES IDENTITY_VAL_LOCAL()
                  DB2: 		VALUES IDENTITY_VAL_LOCAL()
                  DB2_MF:		SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
                  Derby: 		VALUES IDENTITY_VAL_LOCAL()
                  HSQLDB: 	CALL IDENTITY()
                  Informix: 	select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
                  MySql: 		SELECT LAST_INSERT_ID()
                  SqlServer: 	SELECT SCOPE_IDENTITY()
                  SYBASE: 	SELECT @@IDENTITY
                  JDBC:		This will configure MBG to generate code for MyBatis3 suport of JDBC standard generated keys. This is a database independent method of obtaining the value from identity columns.
                  identity: 自增主键  If true, then the column is flagged as an identity column and the generated <selectKey> element will be placed after the insert (for an identity column). If false, then the generated <selectKey> will be placed before the insert (typically for a sequence).

            -->
            <!--<generatedKey column="id" sqlStatement="" identity="" type=""/>-->




            <!-- optional.
                    列的命名规则:
                    MBG使用 <columnRenamingRule> 元素在计算列名的对应 名称之前,先对列名进行重命名,
                    作用:一般需要对BUSI_CLIENT_NO 前的BUSI_进行过滤
                    支持正在表达式
                     searchString 表示要被换掉的字符串
                     replaceString 则是要换成的字符串,默认情况下为空字符串,可选
            -->
          <!--  <columnRenamingRule searchString="" replaceString=""/>-->




            <!-- optional.告诉 MBG 忽略某一列
                    column,需要忽略的列
                    delimitedColumnName:true ,匹配column的值和数据库列的名称 大小写完全匹配,false 忽略大小写匹配
                    是否限定表的列名,即固定表列在Model中的名称
            -->
            <ignoreColumn column="PLAN_ID"  delimitedColumnName="true" />


            <!--optional.覆盖MBG对Model 的生成规则
                 column: 数据库的列名
                 javaType: 对应的Java数据类型的完全限定名
                 在必要的时候可以覆盖由JavaTypeResolver计算得到的java数据类型. For some databases, this is necessary to handle "odd" database types (e.g. MySql's unsigned bigint type should be mapped to java.lang.Object).
                 jdbcType:该列的JDBC数据类型(INTEGER, DECIMAL, NUMERIC, VARCHAR, etc.),该列可以覆盖由JavaTypeResolver计算得到的Jdbc类型,对某些数据库而言,对于处理特定的JDBC 驱动癖好 很有必要(e.g. DB2's LONGVARCHAR type should be mapped to VARCHAR for iBATIS).
                 typeHandler:

            -->
           <!-- <columnOverride column="" javaType=""	jdbcType=""	typeHandler=""	delimitedColumnName="" />-->

        </table>
        <table tableName="info" schema="guihuashi">
        </table>
    </context>
</generatorConfiguration>

    对于一些文章可能并未指出这个生成工具是否能够生成存在外键关系的多表查询,其实是不行的,这也是我为什么开头会介绍关于dao以及service设计的原因,不过我依旧会觉得这个工具还不够方便,待我功力够了,看看能否做个生成工具,解决这个问题。接着是属性文件generator.properties

   

jdbc.driverLocation=C:\\JSP\\mysql-connector-java-5.1.39\\mysql-connector-java-5.1.39\\mysql-connector-java-5.1.39-bin.jar
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc\:mysql\://localhost/guihuashi
jdbc.userId=root
jdbc.password=
    我采用的是itellij来开发的,需要配置运行。点击Run按钮,选择Edit Configurations,点击 " + " 按钮,选择maven

在Name中填入名字,接着在Command line填写mybatis-generator:generate -e这样我们点击apply按钮,就会看到按钮


点击运行,那么我们来看看控制台会出现什么情况?

C:\dazaijava\java\jdk1.8.0_20\bin\java -Dmaven.multiModuleProjectDirectory=C:\源码\zookeeper_java "-Dmaven.home=C:\JetBrains\IntelliJ IDEA 2016.3最新版\plugins\maven\lib\maven3" "-Dclassworlds.conf=C:\JetBrains\IntelliJ IDEA 2016.3最新版\plugins\maven\lib\maven3\bin\m2.conf" -Didea.launcher.port=7532 "-Didea.launcher.bin.path=C:\JetBrains\IntelliJ IDEA 2016.3最新版\bin" -Dfile.encoding=UTF-8 -classpath "C:\JetBrains\IntelliJ IDEA 2016.3最新版\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar;C:\JetBrains\IntelliJ IDEA 2016.3最新版\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=2016.3 mybatis-generator:generate -e
[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for zookeeper_java:zookeeper_java:jar:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.apache.httpcomponents:httpclient:jar -> duplicate declaration of version 4.0.2 @ line 121, column 21
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building zookeeper_java 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ zookeeper_java ---
[INFO] Connecting to the Database
Tue Dec 27 12:52:22 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[INFO] Introspecting table guihuashi.stu
log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[INFO] Introspecting table guihuashi.info
[INFO] Generating Example class for table stu
[INFO] Generating Record class for table stu
[INFO] Generating Mapper Interface for table stu
[INFO] Generating SQL Map for table stu
[INFO] Generating Example class for table info
[INFO] Generating Record class for table info
[INFO] Generating Mapper Interface for table info
[INFO] Generating SQL Map for table info
[INFO] Saving file StuMapper.xml
[INFO] Saving file InfoMapper.xml
[INFO] Saving file StuExample.java
[INFO] Saving file Stu.java
[INFO] Saving file StuMapper.java
[INFO] Saving file InfoExample.java
[INFO] Saving file Info.java
[INFO] Saving file InfoMapper.java
[WARNING] Column PLAN_ID, specified to be ignored in table stu, does not exist in the table.
[WARNING] Root class com.foo.louis.Hello cannot be loaded, checking for member overrides is disabled for this class 
[WARNING] Existing file C:\源码\zookeeper_java\src\main\java\org\louis\hometutor\po\StuExample.java was overwritten
[WARNING] Existing file C:\源码\zookeeper_java\src\main\java\org\louis\hometutor\po\Stu.java was overwritten
[WARNING] Existing file C:\源码\zookeeper_java\src\main\java\com\foo\tourist\dao\StuMapper.java was overwritten
[WARNING] Existing file C:\源码\zookeeper_java\src\main\java\org\louis\hometutor\po\InfoExample.java was overwritten
[WARNING] Existing file C:\源码\zookeeper_java\src\main\java\org\louis\hometutor\po\Info.java was overwritten
[WARNING] Existing file C:\源码\zookeeper_java\src\main\java\com\foo\tourist\dao\InfoMapper.java was overwritten
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.660 s
[INFO] Finished at: 2016-12-27T12:52:24+08:00
[INFO] Final Memory: 6M/19M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

编译成功success,而且我们会在工程里面看到生成的mybatis文件,大功告成,如果编译不成功,根据控制台解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值