GVKun编程网logo

Mybatis 中 Integer 类型参数问题(mybatis integer为0)

9

在本文中,您将会了解到关于Mybatis中Integer类型参数问题的新资讯,同时我们还将为您解释mybatisinteger为0的相关在本文中,我们将带你探索Mybatis中Integer类型参数问

在本文中,您将会了解到关于Mybatis 中 Integer 类型参数问题的新资讯,同时我们还将为您解释mybatis integer为0的相关在本文中,我们将带你探索Mybatis 中 Integer 类型参数问题的奥秘,分析mybatis integer为0的特点,并给出一些关于Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代、Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代码、Intellij IDEA 中使用 MyBatis-generator 自动生成 MyBatis 代码、Intellij IDEA 中使用MyBatis-generator 自动生成MyBatis代的实用技巧。

本文目录一览:

Mybatis 中 Integer 类型参数问题(mybatis integer为0)

Mybatis 中 Integer 类型参数问题(mybatis integer为0)

前两天在项目开发遇到了Mybatis 中 Integer 类型参数传递问题.项目中代码如下

<if test="req.type != null and req.type !=''">
      AND type = #{req.type}
</if>
使用实体类传递参数时,若属性为 varchar 类型,则一般情况下使用上面的写法;若有些属性类型设置为 Integer 类型,如果依旧沿用上面写法,会有以下问题:
1、不传入 state 值(则state为null),则无法进入 if 条件内;
2、传入 state 为 0 以外的数字,则成功进入 if 条件内;
3、传入 state 为 0 ,则无法进入进入 if 条件内,原因:mybatis 在解析Integer类型数据时,如果数据值为0,会将0解析为空字符串。
因此,传递 Integer 类型参数时,正确写法如下:
<if test="req.type != null ">
    AND type = #{req.type}
</if>
 
转载 链接:https://www.jianshu.com/p/491a94c8f740

Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代

Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代

Intellij IDEA 14 作为Java IDE 神器,接触后发现,非常好用,对它爱不释手,打算离开eclipse和myeclipse,投入Intellij IDEA的怀抱。

     然而在使用的过程中会发现Intellij IDEA也有一些不尽如意的地方,难免会有些不爽:Intellij IDEA 的插件库远不及eclipse的丰富。 mybatis-generator在eclipse中有专门的插件,而没有开发出Intellij IDEA能够使用的插件。

    不过不用灰心,如果你的项目是使用maven组织的,那么我们可以在Intellij IDEA中使用 mybatis-generator-maven-plugin插件来完成MyBatis model 和Mapper文件的自动生成。

STEP 0.在Intellij IDEA创建maven项目(本过程比较简单,略)


STEP 1. 在maven项目的pom.xml 添加mybatis-generator-maven-plugin 插件

[html] view plaincopy在CODE上查看代码片派生到我的代码片

  1. <build>  

  2.   <finalName>xxx</finalName>  

  3.   <plugins>  

  4.     <plugin>  

  5.       <groupId>org.mybatis.generator</groupId>  

  6.       <artifactId>mybatis-generator-maven-plugin</artifactId>  

  7.       <version>1.3.2</version>  

  8.       <configuration>  

  9.         <verbose>true</verbose>  

  10.         <overwrite>true</overwrite>  

  11.       </configuration>  

  12.     </plugin>  

  13.   </plugins>  

  14. </build>  


STEP 2. 在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件,作为mybatis-generator-maven-plugin 插件的执行目标,模板如下:


[html] view plaincopy在CODE上查看代码片派生到我的代码片

  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.     <!--导入属性配置 -->  

  7.     <properties resource="generator.properties"></properties>  

  8.   

  9.     <!--指定特定数据库的jdbc驱动jar包的位置 -->  

  10.     <classPathEntry location="${jdbc.driverLocation}"/>  

  11.   

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

  13.   

  14.   

  15.         <!-- optional,旨在创建class时,对注释进行控制 -->  

  16.         <commentGenerator>  

  17.             <property name="suppressDate" value="true" />  

  18.         </commentGenerator>  

  19.   

  20.   

  21.         <!--jdbc的数据库连接 -->  

  22.         <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}">  

  23.         </jdbcConnection>  

  24.   

  25.   

  26.   

  27.         <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->  

  28.         <javaTypeResolver >  

  29.             <property name="forceBigDecimals" value="false" />  

  30.         </javaTypeResolver>  

  31.   

  32.         <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类  

  33.             targetPackage     指定生成的model生成所在的包名  

  34.             targetProject     指定在该项目下所在的路径  

  35.         -->  

  36.         <javaModelGenerator targetPackage="org.louis.hometutor.po" targetProject="src/main/java">  

  37.             <!-- 是否对model添加 构造函数 -->  

  38.             <property name="constructorBased" value="true"/>  

  39.   

  40.             <!-- 是否允许子包,即targetPackage.schemaName.tableName -->  

  41.             <property name="enableSubPackages" value="false"/>  

  42.   

  43.             <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->  

  44.             <property name="immutable" value="true"/>  

  45.   

  46.             <!-- 给Model添加一个父类 -->  

  47.             <property name="rootClass" value="com.foo.louis.Hello"/>  

  48.   

  49.             <!-- 是否对类CHAR类型的列的数据进行trim操作 -->  

  50.             <property name="trimStrings" value="true"/>  

  51.         </javaModelGenerator>  

  52.   

  53.         <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->  

  54.         <sqlMapGenerator targetPackage="org.louis.hometutor.domain" targetProject="src/main/java">  

  55.             <property name="enableSubPackages" value="false"/>  

  56.         </sqlMapGenerator>  

  57.   

  58.   

  59.         <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码  

  60.                 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象  

  61.                 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象  

  62.                 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口  

  63.         -->  

  64.         <javaClientGenerator targetPackage="com.foo.tourist.dao" targetProject="src/main/java" type="MIXEDMAPPER">  

  65.             <property name="enableSubPackages" value=""/>  

  66.             <!--  

  67.                     定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:  

  68.                     public;  

  69.                     private;  

  70.                     protected;  

  71.                     default  

  72.                     注意:如果 targetRuntime="MyBatis3",此参数被忽略  

  73.              -->  

  74.             <property name="exampleMethodVisibility" value=""/>  

  75.             <!--  

  76.                                            方法名计数器  

  77.               Important note: this property is ignored if the target runtime is MyBatis3.  

  78.              -->  

  79.             <property name="methodNameCalculator" value=""/>  

  80.   

  81.             <!-- 

  82.                                                 为生成的接口添加父接口 

  83.              -->  

  84.             <property name="rootInterface" value=""/>  

  85.   

  86.         </javaClientGenerator>  

  87.   

  88.   

  89.   

  90.         <table tableName="lession" schema="louis">  

  91.   

  92.             <!-- optional   , only for mybatis3 runtime  

  93.                  自动生成的键值(identity,或者序列值)  

  94.                如果指定此元素,MBG将会生成<selectKey>元素,然后将此元素插入到SQL Map的<insert> 元素之中  

  95.                sqlStatement 的语句将会返回新的值  

  96.                如果是一个自增主键的话,你可以使用预定义的语句,或者添加自定义的SQL语句. 预定义的值如下:  

  97.                   Cloudscape    This will translate to: VALUES IDENTITY_VAL_LOCAL()  

  98.                   DB2:      VALUES IDENTITY_VAL_LOCAL()  

  99.                   DB2_MF:       SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1  

  100.                   Derby:        VALUES IDENTITY_VAL_LOCAL()  

  101.                   HSQLDB:   CALL IDENTITY()  

  102.                   Informix:     select dbinfo(''sqlca.sqlerrd1'') from systables where tabid=1  

  103.                   MySql:        SELECT LAST_INSERT_ID()  

  104.                   SqlServer:    SELECT SCOPE_IDENTITY()  

  105.                   SYBASE:   SELECT @@IDENTITY  

  106.                   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.  

  107.                   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).  

  108.   

  109.             -->  

  110.             <generatedKey column="" sqlStatement="" identity="" type=""/>  

  111.   

  112.   

  113.             <!-- optional.  

  114.                     列的命名规则:  

  115.                     MBG使用 <columnRenamingRule> 元素在计算列名的对应 名称之前,先对列名进行重命名,  

  116.                     作用:一般需要对BUSI_CLIENT_NO 前的BUSI_进行过滤  

  117.                     支持正在表达式  

  118.                      searchString 表示要被换掉的字符串  

  119.                      replaceString 则是要换成的字符串,默认情况下为空字符串,可选  

  120.             -->  

  121.             <columnRenamingRule searchString="" replaceString=""/>  

  122.   

  123.   

  124.   

  125.             <!-- optional.告诉 MBG 忽略某一列  

  126.                     column,需要忽略的列  

  127.                     delimitedColumnName:true ,匹配column的值和数据库列的名称 大小写完全匹配,false 忽略大小写匹配  

  128.                     是否限定表的列名,即固定表列在Model中的名称  

  129.             -->  

  130.             <ignoreColumn column="PLAN_ID"  delimitedColumnName="true" />  

  131.   

  132.   

  133.             <!--optional.覆盖MBG对Model 的生成规则  

  134.                  column: 数据库的列名  

  135.                  javaType: 对应的Java数据类型的完全限定名  

  136.                  在 必要的时候可以覆盖由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).  

  137.                  jdbcType: 该列的JDBC数据类型(INTEGER, DECIMAL, NUMERIC, VARCHAR, etc.),该列可以覆盖由 JavaTypeResolver计算得到的Jdbc类型,对某些数据库而言,对于处理特定的JDBC 驱动癖好 很有必要 (e.g. DB2''s LONGVARCHAR type should be mapped to VARCHAR for iBATIS).  

  138.                  typeHandler:  

  139.   

  140.             -->  

  141.             <columnOverride column="" javaType=""    jdbcType="" typeHandler=""  delimitedColumnName="" />  

  142.   

  143.         </table>  

  144.     </context>  

  145. </generatorConfiguration>  


这里使用了外置的配置文件generator.properties,可以将一下属性配置到properties文件之中,增加配置的灵活性:

[plain] view plaincopy在CODE上查看代码片派生到我的代码片

  1. jdbc.driverLocation=D:\\maven\\com\\oracle\\ojdbc14\\10.2.0.4.0\\ojdbc14-10.2.0.4.0.jar  

  2. jdbc.driverClass=oracle.jdbc.driver.OracleDriver  

  3. jdbc.connectionURL=jdbc:oracle:thin:@//localhost:1521/XE  

  4. jdbc.userId=LOUIS  

  5. jdbc.password=123456  


项目目录如下:

技术分享




STEP 3. 在Intellij IDEA添加一个“Run运行”选项,使用maven运行mybatis-generator-maven-plugin插件 :


技术分享

技术分享

之后弹出运行配置框,为当前配置配置一个名称,这里其名为"generator",然后在 “Command line” 选项中输入“mybatis-generator:generate  -e

这里加了“-e ”选项是为了让该插件输出详细信息,这样可以帮助我们定位问题。

技术分享

技术分享

如果添加成功,则会在run 选项中有“generator” 选项,如下:

技术分享

点击运行,然后不出意外的话,会在控制台输出:

[plain] view plaincopy在CODE上查看代码片派生到我的代码片

  1. C:\Java\jdk1.7.0_71\bin\java -Dmaven.home=D:\software\apache-maven-3.0.5-bin -Dclassworlds.conf=D:\software\apache-maven-3.0.5-bin\bin\m2.conf -Didea.launcher.port=7533 "-Didea.launcher.bin.path=D:\applications\JetBrains\IntelliJ IDEA 14.0.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\software\apache-maven-3.0.5-bin\boot\plexus-classworlds-2.4.jar;D:\applications\JetBrains\IntelliJ IDEA 14.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=14.0.2 -s D:\software\apache-maven-3.0.5-bin\conf\settings.xml mybatis-generator:generate -e  

  2. [INFO] Error stacktraces are turned on.  

  3. [INFO] Scanning for projects...  

  4. [INFO]                                                                           

  5. [INFO] ------------------------------------------------------------------------  

  6. [INFO] Building hometutor Maven Webapp 1.0-SNAPSHOT  

  7. [INFO] ------------------------------------------------------------------------  

  8. [INFO]   

  9. [INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ hometutor ---  

  10. [INFO] Connecting to the Database  

  11. [INFO] Introspecting table louis.lession  

  12. log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).  

  13. log4j:WARN Please initialize the log4j system properly.  

  14. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.  

  15. [INFO] Generating Example class for table LOUIS.LESSION  

  16. [INFO] Generating Record class for table LOUIS.LESSION  

  17. [INFO] Generating Mapper Interface for table LOUIS.LESSION  

  18. [INFO] Generating SQL Map for table LOUIS.LESSION  

  19. [INFO] Saving file LessionMapper.xml  

  20. [INFO] Saving file LessionExample.java  

  21. [INFO] Saving file Lession.java  

  22. [INFO] Saving file LessionMapper.java  

  23. [WARNING] Root class com.foo.louis.Hello cannot be loaded, checking for member overrides is disabled for this class   

  24. [WARNING] Existing file E:\sources\tutor\src\main\java\org\louis\hometutor\po\Lession.java was overwritten  

  25. [WARNING] Existing file E:\sources\tutor\src\main\java\com\foo\tourist\dao\LessionMapper.java was overwritten  

  26. [INFO] ------------------------------------------------------------------------  

  27. [INFO] BUILD SUCCESS  

  28. [INFO] ------------------------------------------------------------------------  

  29. [INFO] Total time: 2.334s  

  30. [INFO] Finished at: Tue Jan 27 12:04:08 CST 2015  

  31. [INFO] Final Memory: 8M/107M  

  32. [INFO] ------------------------------------------------------------------------  

  33.   

  34. Process finished with exit code 0  

好,看到BUILD SUCCESS,则大功告成,如果有错误的话,由于添加了-e 选项,会把具体的详细错误信息打印出来的,根据错误信息修改即可


Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代码

Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代码

Intellij IDEA 14 作为Java IDE 神器,接触后发现,非常好用,对它爱不释手,打算离开eclipse和myeclipse,投入Intellij IDEA的怀抱。

     然而在使用的过程中会发现Intellij IDEA也有一些不尽如意的地方,难免会有些不爽:Intellij IDEA 的插件库远不及eclipse的丰富。 mybatis-generator在eclipse中有专门的插件,而没有开发出Intellij IDEA能够使用的插件。

    不过不用灰心,如果你的项目是使用maven组织的,那么我们可以在Intellij IDEA中使用 mybatis-generator-maven-plugin插件来完成MyBatis model 和Mapper文件的自动生成。


STEP 0.在Intellij IDEA创建maven项目(本过程比较简单,略)


STEP 1. 在maven项目的pom.xml 添加mybatis-generator-maven-plugin 插件

<build>
    <finalName>xxx</finalName>
    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>
    </plugins>
  </build>


STEP 2. 在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件,作为mybatis-generator-maven-plugin 插件的执行目标,模板如下:


<?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 driverconnectionURL="${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="lession" schema="louis">

            <!-- 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="" 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>
    </context>
</generatorConfiguration>


这里使用了外置的配置文件generator.properties,可以将一下属性配置到properties文件之中,增加配置的灵活性:

jdbc.driverLocation=D:\\maven\\com\\oracle\\ojdbc14\\10.2.0.4.0\\ojdbc14-10.2.0.4.0.jar
jdbc.driverClass=oracle.jdbc.driver.OracleDriver
jdbc.connectionURL=jdbc:oracle:thin:@//localhost:1521/XE
jdbc.userId=LOUIS
jdbc.password=123456

项目目录如下:

技术分享




STEP 3. 在Intellij IDEA添加一个“Run运行”选项,使用maven运行mybatis-generator-maven-plugin插件 :


技术分享

技术分享

之后弹出运行配置框,为当前配置配置一个名称,这里其名为"generator",然后在 “Command line” 选项中输入“mybatis-generator:generate  -e

这里加了“-e ”选项是为了让该插件输出详细信息,这样可以帮助我们定位问题。

技术分享

技术分享

如果添加成功,则会在run 选项中有“generator” 选项,如下:

技术分享

点击运行,然后不出意外的话,会在控制台输出:

C:\Java\jdk1.7.0_71\bin\java -Dmaven.home=D:\software\apache-maven-3.0.5-bin -Dclassworlds.conf=D:\software\apache-maven-3.0.5-bin\bin\m2.conf -Didea.launcher.port=7533 "-Didea.launcher.bin.path=D:\applications\JetBrains\IntelliJ IDEA 14.0.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\software\apache-maven-3.0.5-bin\boot\plexus-classworlds-2.4.jar;D:\applications\JetBrains\IntelliJ IDEA 14.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=14.0.2 -s D:\software\apache-maven-3.0.5-bin\conf\settings.xml mybatis-generator:generate -e
[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building hometutor Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ hometutor ---
[INFO] Connecting to the Database
[INFO] Introspecting table louis.lession
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] Generating Example class for table LOUIS.LESSION
[INFO] Generating Record class for table LOUIS.LESSION
[INFO] Generating Mapper Interface for table LOUIS.LESSION
[INFO] Generating SQL Map for table LOUIS.LESSION
[INFO] Saving file LessionMapper.xml
[INFO] Saving file LessionExample.java
[INFO] Saving file Lession.java
[INFO] Saving file LessionMapper.java
[WARNING] Root class com.foo.louis.Hello cannot be loaded, checking for member overrides is disabled for this class 
[WARNING] Existing file E:\sources\tutor\src\main\java\org\louis\hometutor\po\Lession.java was overwritten
[WARNING] Existing file E:\sources\tutor\src\main\java\com\foo\tourist\dao\LessionMapper.java was overwritten
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.334s
[INFO] Finished at: Tue Jan 27 12:04:08 CST 2015
[INFO] Final Memory: 8M/107M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

好,看到BUILD SUCCESS,则大功告成,如果有错误的话,由于添加了-e 选项,会把具体的详细错误信息打印出来的,根据错误信息修改即可

Intellij IDEA 中使用 MyBatis-generator 自动生成 MyBatis 代码

Intellij IDEA 中使用 MyBatis-generator 自动生成 MyBatis 代码

1、IDEA创建maven工程(略)

2、 在maven项目的pom.xml 添加mybatis-generator-maven-plugin 插件和MySQL数据库驱动依赖

<build>
  <plugins>
    <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>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.34</version>
</dependency>

3、在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件,作为mybatis-generator-maven-plugin 插件的执行目标,模板如下:

<?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>
    <!-- 配置mysql 驱动jar包路径.用了绝对路径 -->
    <classPathEntry location="/Users/wangyongzhi/.m2/repository/mysql/mysql-connector-java/5.1.34/mysql-connector-java-5.1.34.jar" />
  
    <context id="wangyongzhi_mysql_tables" targetRuntime="MyBatis3">
        <!-- 防止生成的代码中有很多注释,加入下面的配置控制 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
            <property name="suppressDate" value="true" />
        </commentGenerator>

        <!-- 数据库连接 -->
        <jdbcConnection driverconnectionURL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 数据表对应的model层  -->
        <javaModelGenerator targetPackage="me.zhige.domain" targetProject="src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- sql mapper 映射配置文件 -->
        <sqlMapGenerator targetPackage="me.zhige.mapper"  targetProject="src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- mybatis3中的mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="me.zhige.dao"  targetProject="src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 数据表进行生成操作 schema:相当于库名; tableName:表名; domainObjectName:对应的DO -->
        <table schema="test" tableName="users" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>

4、使用maven运行mybatis-generator-maven-plugin插件:工程名->Plugins->mybatis-generator->mybatis-generator:generate->Run Maven Build

图片发自简书App

5、自动生成的结构如下:

img

福利:我这里有一些电子书的存货,估计有上万本吧,各个类型的都有,关注我的公众号「志哥的成长笔记」(ID:zhige-me),后台回复 「阅读」 获取。扫描下方二维码关注。

Intellij IDEA 中使用MyBatis-generator 自动生成MyBatis代

Intellij IDEA 中使用MyBatis-generator 自动生成MyBatis代

ntellij IDEA 14 作为Java IDE 神器,接触后发现,非常好用,对它爱不释手,打算离开eclipse和myeclipse,投入Intellij IDEA的怀抱。

     然而在使用的过程中会发现Intellij IDEA也有一些不尽如意的地方,难免会有些不爽:Intellij IDEA 的插件库远不及eclipse的丰富。 mybatis-generator在eclipse中有专门的插件,而没有开发出Intellij IDEA能够使用的插件。

    不过不用灰心,如果你的项目是使用maven组织的,那么我们可以在Intellij IDEA中使用 mybatis-generator-maven-plugin插件来完成MyBatis model 和Mapper文件的自动生成。


STEP 0.在Intellij IDEA创建maven项目(本过程比较简单,略)


STEP 1. 在maven项目的pom.xml 添加mybatis-generator-maven-plugin 插件

[html] view plaincopy在CODE上查看代码片派生到我的代码片

  1. <build>  

  2.   <finalName>xxx</finalName>  

  3.   <plugins>  

  4.     <plugin>  

  5.       <groupId>org.mybatis.generator</groupId>  

  6.       <artifactId>mybatis-generator-maven-plugin</artifactId>  

  7.       <version>1.3.2</version>  

  8.       <configuration>  

  9.         <verbose>true</verbose>  

  10.         <overwrite>true</overwrite>  

  11.       </configuration>  

  12.     </plugin>  

  13.   </plugins>  

  14. </build>  


STEP 2. 在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件,作为mybatis-generator-maven-plugin 插件的执行目标,模板如下:


[html] view plaincopy在CODE上查看代码片派生到我的代码片

  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.     <!--导入属性配置 -->  

  7.     <properties resource="generator.properties"></properties>  

  8.   

  9.     <!--指定特定数据库的jdbc驱动jar包的位置 -->  

  10.     <classPathEntry location="${jdbc.driverLocation}"/>  

  11.   

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

  13.   

  14.   

  15.         <!-- optional,旨在创建class时,对注释进行控制 -->  

  16.         <commentGenerator>  

  17.             <property name="suppressDate" value="true" />  

  18.         </commentGenerator>  

  19.   

  20.   

  21.         <!--jdbc的数据库连接 -->  

  22.         <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}">  

  23.         </jdbcConnection>  

  24.   

  25.   

  26.   

  27.         <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->  

  28.         <javaTypeResolver >  

  29.             <property name="forceBigDecimals" value="false" />  

  30.         </javaTypeResolver>  

  31.   

  32.         <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类  

  33.             targetPackage     指定生成的model生成所在的包名  

  34.             targetProject     指定在该项目下所在的路径  

  35.         -->  

  36.         <javaModelGenerator targetPackage="org.louis.hometutor.po" targetProject="src/main/java">  

  37.             <!-- 是否对model添加 构造函数 -->  

  38.             <property name="constructorBased" value="true"/>  

  39.   

  40.             <!-- 是否允许子包,即targetPackage.schemaName.tableName -->  

  41.             <property name="enableSubPackages" value="false"/>  

  42.   

  43.             <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->  

  44.             <property name="immutable" value="true"/>  

  45.   

  46.             <!-- 给Model添加一个父类 -->  

  47.             <property name="rootClass" value="com.foo.louis.Hello"/>  

  48.   

  49.             <!-- 是否对类CHAR类型的列的数据进行trim操作 -->  

  50.             <property name="trimStrings" value="true"/>  

  51.         </javaModelGenerator>  

  52.   

  53.         <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->  

  54.         <sqlMapGenerator targetPackage="org.louis.hometutor.domain" targetProject="src/main/java">  

  55.             <property name="enableSubPackages" value="false"/>  

  56.         </sqlMapGenerator>  

  57.   

  58.   

  59.         <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码  

  60.                 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象  

  61.                 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象  

  62.                 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口  

  63.         -->  

  64.         <javaClientGenerator targetPackage="com.foo.tourist.dao" targetProject="src/main/java" type="MIXEDMAPPER">  

  65.             <property name="enableSubPackages" value=""/>  

  66.             <!--  

  67.                     定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:  

  68.                     public;  

  69.                     private;  

  70.                     protected;  

  71.                     default  

  72.                     注意:如果 targetRuntime="MyBatis3",此参数被忽略  

  73.              -->  

  74.             <property name="exampleMethodVisibility" value=""/>  

  75.             <!--  

  76.                                            方法名计数器  

  77.               Important note: this property is ignored if the target runtime is MyBatis3.  

  78.              -->  

  79.             <property name="methodNameCalculator" value=""/>  

  80.   

  81.             <!-- 

  82.                                                 为生成的接口添加父接口 

  83.              -->  

  84.             <property name="rootInterface" value=""/>  

  85.   

  86.         </javaClientGenerator>  

  87.   

  88.   

  89.   

  90.         <table tableName="lession" schema="louis">  

  91.   

  92.             <!-- optional   , only for mybatis3 runtime  

  93.                  自动生成的键值(identity,或者序列值)  

  94.                如果指定此元素,MBG将会生成<selectKey>元素,然后将此元素插入到SQL Map的<insert> 元素之中  

  95.                sqlStatement 的语句将会返回新的值  

  96.                如果是一个自增主键的话,你可以使用预定义的语句,或者添加自定义的SQL语句. 预定义的值如下:  

  97.                   Cloudscape    This will translate to: VALUES IDENTITY_VAL_LOCAL()  

  98.                   DB2:      VALUES IDENTITY_VAL_LOCAL()  

  99.                   DB2_MF:       SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1  

  100.                   Derby:        VALUES IDENTITY_VAL_LOCAL()  

  101.                   HSQLDB:   CALL IDENTITY()  

  102.                   Informix:     select dbinfo(''sqlca.sqlerrd1'') from systables where tabid=1  

  103.                   MySql:        SELECT LAST_INSERT_ID()  

  104.                   SqlServer:    SELECT SCOPE_IDENTITY()  

  105.                   SYBASE:   SELECT @@IDENTITY  

  106.                   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.  

  107.                   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).  

  108.   

  109.             -->  

  110.             <generatedKey column="" sqlStatement="" identity="" type=""/>  

  111.   

  112.   

  113.             <!-- optional.  

  114.                     列的命名规则:  

  115.                     MBG使用 <columnRenamingRule> 元素在计算列名的对应 名称之前,先对列名进行重命名,  

  116.                     作用:一般需要对BUSI_CLIENT_NO 前的BUSI_进行过滤  

  117.                     支持正在表达式  

  118.                      searchString 表示要被换掉的字符串  

  119.                      replaceString 则是要换成的字符串,默认情况下为空字符串,可选  

  120.             -->  

  121.             <columnRenamingRule searchString="" replaceString=""/>  

  122.   

  123.   

  124.   

  125.             <!-- optional.告诉 MBG 忽略某一列  

  126.                     column,需要忽略的列  

  127.                     delimitedColumnName:true ,匹配column的值和数据库列的名称 大小写完全匹配,false 忽略大小写匹配  

  128.                     是否限定表的列名,即固定表列在Model中的名称  

  129.             -->  

  130.             <ignoreColumn column="PLAN_ID"  delimitedColumnName="true" />  

  131.   

  132.   

  133.             <!--optional.覆盖MBG对Model 的生成规则  

  134.                  column: 数据库的列名  

  135.                  javaType: 对应的Java数据类型的完全限定名  

  136.                  在 必要的时候可以覆盖由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).  

  137.                  jdbcType: 该列的JDBC数据类型(INTEGER, DECIMAL, NUMERIC, VARCHAR, etc.),该列可以覆盖由 JavaTypeResolver计算得到的Jdbc类型,对某些数据库而言,对于处理特定的JDBC 驱动癖好 很有必要 (e.g. DB2''s LONGVARCHAR type should be mapped to VARCHAR for iBATIS).  

  138.                  typeHandler:  

  139.   

  140.             -->  

  141.             <columnOverride column="" javaType=""    jdbcType="" typeHandler=""  delimitedColumnName="" />  

  142.   

  143.         </table>  

  144.     </context>  

  145. </generatorConfiguration>  


这里使用了外置的配置文件generator.properties,可以将一下属性配置到properties文件之中,增加配置的灵活性:

[plain] view plaincopy在CODE上查看代码片派生到我的代码片

  1. jdbc.driverLocation=D:\\maven\\com\\oracle\\ojdbc14\\10.2.0.4.0\\ojdbc14-10.2.0.4.0.jar  

  2. jdbc.driverClass=oracle.jdbc.driver.OracleDriver  

  3. jdbc.connectionURL=jdbc:oracle:thin:@//localhost:1521/XE  

  4. jdbc.userId=LOUIS  

  5. jdbc.password=123456  


项目目录如下:

技术分享




STEP 3. 在Intellij IDEA添加一个“Run运行”选项,使用maven运行mybatis-generator-maven-plugin插件 :


技术分享

技术分享

之后弹出运行配置框,为当前配置配置一个名称,这里其名为"generator",然后在 “Command line” 选项中输入“mybatis-generator:generate  -e

这里加了“-e ”选项是为了让该插件输出详细信息,这样可以帮助我们定位问题。

技术分享

技术分享

如果添加成功,则会在run 选项中有“generator” 选项,如下:

技术分享

点击运行,然后不出意外的话,会在控制台输出:

[plain] view plaincopy在CODE上查看代码片派生到我的代码片

  1. C:\Java\jdk1.7.0_71\bin\java -Dmaven.home=D:\software\apache-maven-3.0.5-bin -Dclassworlds.conf=D:\software\apache-maven-3.0.5-bin\bin\m2.conf -Didea.launcher.port=7533 "-Didea.launcher.bin.path=D:\applications\JetBrains\IntelliJ IDEA 14.0.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\software\apache-maven-3.0.5-bin\boot\plexus-classworlds-2.4.jar;D:\applications\JetBrains\IntelliJ IDEA 14.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=14.0.2 -s D:\software\apache-maven-3.0.5-bin\conf\settings.xml mybatis-generator:generate -e  

  2. [INFO] Error stacktraces are turned on.  

  3. [INFO] Scanning for projects...  

  4. [INFO]                                                                           

  5. [INFO] ------------------------------------------------------------------------  

  6. [INFO] Building hometutor Maven Webapp 1.0-SNAPSHOT  

  7. [INFO] ------------------------------------------------------------------------  

  8. [INFO]   

  9. [INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ hometutor ---  

  10. [INFO] Connecting to the Database  

  11. [INFO] Introspecting table louis.lession  

  12. log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).  

  13. log4j:WARN Please initialize the log4j system properly.  

  14. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.  

  15. [INFO] Generating Example class for table LOUIS.LESSION  

  16. [INFO] Generating Record class for table LOUIS.LESSION  

  17. [INFO] Generating Mapper Interface for table LOUIS.LESSION  

  18. [INFO] Generating SQL Map for table LOUIS.LESSION  

  19. [INFO] Saving file LessionMapper.xml  

  20. [INFO] Saving file LessionExample.java  

  21. [INFO] Saving file Lession.java  

  22. [INFO] Saving file LessionMapper.java  

  23. [WARNING] Root class com.foo.louis.Hello cannot be loaded, checking for member overrides is disabled for this class   

  24. [WARNING] Existing file E:\sources\tutor\src\main\java\org\louis\hometutor\po\Lession.java was overwritten  

  25. [WARNING] Existing file E:\sources\tutor\src\main\java\com\foo\tourist\dao\LessionMapper.java was overwritten  

  26. [INFO] ------------------------------------------------------------------------  

  27. [INFO] BUILD SUCCESS  

  28. [INFO] ------------------------------------------------------------------------  

  29. [INFO] Total time: 2.334s  

  30. [INFO] Finished at: Tue Jan 27 12:04:08 CST 2015  

  31. [INFO] Final Memory: 8M/107M  

  32. [INFO] ------------------------------------------------------------------------  

  33.   

  34. Process finished with exit code 0  

好,看到BUILD SUCCESS,则大功告成,如果有错误的话,由于添加了-e 选项,会把具体的详细错误信息打印出来的,根据错误信息修改即可


关于Mybatis 中 Integer 类型参数问题mybatis integer为0的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代、Intellij IDEA 14中使用MyBatis-generator 自动生成MyBatis代码、Intellij IDEA 中使用 MyBatis-generator 自动生成 MyBatis 代码、Intellij IDEA 中使用MyBatis-generator 自动生成MyBatis代等相关内容,可以在本站寻找。

本文标签: