1. 程式人生 > >MyBatis自動生成Entity、Dao、Mapping

MyBatis自動生成Entity、Dao、Mapping

  新接的專案使用了MyBatis,Mybatis屬於半自動ORM,在使用這個框架中,工作量最大的就是書寫Mapping的對映檔案,對於其中最基礎的Entity,以及最基礎的CRUD,我們可以利用Mybatis-Generator來幫我們自動生成檔案。

  首先下載相關檔案:http://pan.baidu.com/s/1eRyqYY2

  開啟lib檔案,配置generatorConfig.xml,修改相應的資料庫連線和要生成的表名和類名。

<span style="font-size:18px;"><?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>  
<!-- 資料庫驅動-->  
    <classPathEntry  location="mysql-connector-java-5.1.25-bin.jar"/>  
    <context id="DB2Tables"  targetRuntime="MyBatis3">  
        <commentGenerator>  
            <property name="suppressDate" value="true"/>  
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->  
            <property name="suppressAllComments" value="true"/>  
        </commentGenerator>  
        <!--資料庫連結URL,使用者名稱、密碼 -->  
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://117.169.**.***:3306/mdydb" userId="root" password="******">  
        </jdbcConnection>  
        <javaTypeResolver>  
            <property name="forceBigDecimals" value="false"/>  
        </javaTypeResolver>  
        <!-- 生成模型的包名和位置-->  
        <javaModelGenerator targetPackage="com.mdy.entity" targetProject="src">  
            <property name="enableSubPackages" value="true"/>  
            <property name="trimStrings" value="true"/>  
        </javaModelGenerator>  
        <!-- 生成對映檔案的包名和位置-->  
        <sqlMapGenerator targetPackage="com.mdy.mapping" targetProject="src">  
            <property name="enableSubPackages" value="true"/>  
        </sqlMapGenerator>  
        <!-- 生成DAO的包名和位置-->  
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mdy.dao" targetProject="src">  
            <property name="enableSubPackages" value="true"/>  
        </javaClientGenerator>  
        <!-- 要生成的表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名-->  
        <table tableName="t_user_status" domainObjectName="UserStatus" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration></span>

  然後,在該目錄下建立對應的資料夾,比如我的就是com,mdy,dao、entity、mapping

  接著,在該目錄下執行命令

<span style="font-size:18px;">java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite</span>
  檢視資料夾,即可看到對應的類和xml已經生成好了。