標籤:entity pre pad 基礎上 sage type gre cto 檔案
一、建立測試專案
建立Maven項目MybatisDemo2,修改pom.xml引入依賴。dependencies在上節基礎上新增
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version></dependency>
build添加plugin
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>${basedir}/src/main/resources/config/mybatis-generator-config.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> </dependencies> </plugin> </plugins></build>
configurationFile節點指定了mybatis generator設定檔的路徑
二、添加MBG設定檔
運行MBG主要依靠一份設定檔,這也是學習MBG的關鍵。官方詳細的配置說明:http://www.mybatis.org/generator/configreference/xmlconfig.html
我們在上一步中配置了mybatis generator設定檔的目錄${basedir}/src/main/resources/mybatis-generator-config.xml,現在就在對應目錄建立該xml檔案。內容如下:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!--mybatis產生工具的協助文檔可以看:--> <!--英文:http://www.mybatis.org/generator/usage/mysql.html--> <!--中文:http://www.mybatis.tk/--> <!--中文:http://mbg.cndocs.tk/--><context id="context" targetRuntime="MyBatis3"><!--設定編碼格式--><property name="javaFileEncoding" value="UTF-8"/> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/store"userId="root" password="root"/><!--要產生的 domain 模組位置--><javaModelGenerator targetPackage="com.data.pojo" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> <property name="comments" value="true"/> </javaModelGenerator><!--要產生的 Mapper.xml 檔案位置--><sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator><!--要產生的 Mapper 介面類--><javaClientGenerator targetPackage="com.data.mapper" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <table tableName="category" enableCountByExample="true" enableDeleteByExample="true" enableSelectByExample="true" enableUpdateByExample="true"> <generatedKey column="Id" sqlStatement="mysql" identity="true"/> </table> </context></generatorConfiguration>
其中幾個關鍵節點:
1.jdbcConnection:每個context必須有一個jdbcConnection節點,用來指定資料庫連接所需的資料庫連接屬性。
2. javaModelGenerator:用於定義產生 model類的設定。
3.sqlMapGenerator: 用於定義SQL映射產生器的屬性
4. javaClientGenerator: 用於定義 Java 產生用戶端程式碼器的屬性。 Java用戶端產生器產生Java介面和類,它可以簡單地使用產生的Java模型和XML對應檔。
5.table: 用來從資料庫中選擇一個表。
三、運行外掛程式
我用的IDE是IntelliJ IDEA,可以在Maven 面板雙擊mybatis-generator:gennerate,就會自動產生mybatis相關檔案。
執行完成後效果如下:
JAVA入門[7]-Mybatis generator(MBG)自動產生mybatis代碼