Intellij IDEA 14中使用MyBatis-generator 自動生成MyBatis程式碼
阿新 • • 發佈:2018-12-30
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 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="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 選項,會把具體的詳細錯誤資訊打印出來的,根據錯誤資訊修改即可