使用mybatis-generator自動生成實體類,介面實現類和Mapper對映配置檔案
阿新 • • 發佈:2018-12-25
使用mybatis-generator生成實體類,DAO實現類和Mapper對映
Mybatis-generator外掛依據Java實體類和資料庫表的對映關係,將實體類的屬性和資料表中列名一一對應,執行後自動生成model,DAO和Mapper.xml,對配置Mybatis框架,非常方便實用。下面是我使用該外掛配置Mybatis的方法。
1. 相關檔案準備
先準備兩個jar包,在官網www.mybatis.org 上下載mybatis-generator最新版本的jar包並準備新版的jdbc驅動,並在同一目錄下分別新建名為generatorConfig.xml配置檔案 ,run.cmd的批處理檔案和src的資料夾,如圖所示。然後,編輯run.cmd,鍵入java
-jarmybatis-generator-core-1.3.4.jar -configfile generatorConfig.xml -overwrite後儲存,留著用來執行此外掛。
2. 配置generatorConfig.xml檔案
準備相應的資料庫引數和表,就可以開始配置了:<?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> <!-- 資料庫的JDBC驅動 --> <classPathEntry location="D:\Java\JARS\mybatis-work\mysql-connector-java-5.1.34.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <!--註釋生成器--> <commentGenerator> <!-- 是否去除自動生成的註釋 true:是 false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 資料庫連線的資訊:URL、使用者名稱、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8" userId="root" password="bamboo"> </jdbcConnection> <!-- 型別解析器,預設false就行 --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 自動生成程式碼的位置(包名路徑),實體的路徑 --> <javaModelGenerator targetPackage="entity" targetProject="src"> <!-- 是否讓schems作為包的字尾 --> <property name="enableSubPackages" value="true" /> <!-- 從資料庫返回的值被清理前後的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- map xml生成器 --> <sqlMapGenerator targetPackage="dao" targetProject="src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- DAO介面生成器 --> <javaClientGenerator type="XMLMAPPER" targetPackage="dao" targetProject="src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- tableName用於自動生成程式碼的資料庫表,domainObjectName對應資料庫表的javaBean類名,下面生成兩個表 --> <table tableName="SHOPKEEPER" domainObjectName="Shopkeeper" enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> <table tableName="PRODUCT" domainObjectName="Product" enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
3. 生成程式碼
檢查第2步所用配置無誤並另存為utf-8編碼格式的檔案,再檢查所用資料庫表各有一個主鍵後,雙擊執行批處理檔案run.cmd就可以在src資料夾下生成所需程式碼。下次還需配置Mybatis時,只需清空src資料夾並更改第2步中所用的資料庫和資料庫表就行了。
(完)