Mybatis屬於半自動ORM,在使用這個框架中,工作量最大的就是書寫Mapping的映射文件,由於手動書寫很容易出錯,我們可以利用Mybatis-Generator來幫我們自動生成文件。通過在Eclipse中集成mybatis-generater插件,自動生成Mybatis相關的pojo、dao、Mapper.xml等文件,能夠減少出錯,減少開發工作量。
一、准備工作
Mybatis代碼自動生成需要依賴於mybatis generator,Mybatis-Generator提供了eclipse插件。先獲取插件,然后安裝該插件。
1、獲取mybatis generator eclipse插件
可以通過此地址 http://pan.baidu.com/s/1c0cjDEK?errno=0&errmsg=Auth%20Login%20Sucess&&bduss=&ssnerror=0
2. 在eclipse中安裝插件剛剛下載的插件
3.找到自己的eclipse安裝路徑
4.將獲取的eclipse插件解壓拷貝到eclipse安裝目錄
5.替換后重啟eclipse,在eclipse中點擊“File”-“New”-“Other”在類型選擇欄里可以看到Mybatis目錄和MyBatis Generator Configuration File就說明插件已經安裝成功了。
二、代碼生成
1. 在ecplise中新建一個名為MybatisModel 的Dynamic Web Project工程。引入MySQL-connector-Java-5.1.34.jar的mysql驅動包,通過在eclipse中點擊“File”-“New”-“Other”在類型選擇欄里選擇Mybatis目錄下的MyBatis Generator Configuration File生成一個generatorConfig.xml的配置文件。
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> <!-- 數據庫驅動 注意:這個 location要指明\MySQL-connector-Java jar包的絕對路徑--> <classPathEntry location="C:\Users\hp\.m2\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.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://localhost:3306/test" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置 這個targetProject一定不要寫錯:這里應該是寫你的工程名字--> <javaModelGenerator targetPackage="com.yatang.pojo" targetProject="test"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="com.yatang.mapper" targetProject="test"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yatang.dao" targetProject="test"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名--> <table tableName="u_permission" domainObjectName="Upermission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
3. 配置完成后,在generatorConfig.xml的配置文件上點擊右鍵選擇“Generate MyBatis/iBATIS Artifacts”就可以生成相應的代碼。
4. 生成的代碼結構如下圖所示:
5. Mapper.xml中的單表的增加、修改、刪除都已經自動生成了。相應的model和dao層的代碼都已經生成了。
6. 剩下要做的就是只需要將生成的代碼挪到自己的工程中進行修改調試了。
不足之處請大家指出來 共同學習 共同進步 ~
-