eclipse下maven外掛用mybatis-generator生成程式碼
阿新 • • 發佈:2018-11-17
眾所眾知,mybatis是半自動的ORM持久化框架,不像hibernate可以全自動根據庫表生產pojo實體類或根據pojo實體類反向生成庫表。
不過我們可以利用maven外掛的mybatis-generator功能生成mybatis的xml對映檔案和資料庫對應的實體類。
下面請看生成程式碼的具體步驟:
1.新建maven專案
2.在pom.xml新增外掛
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId >mybatis-generator-maven-plugin</artifactId>
<configuration>
<!--允許覆蓋生成的檔案 -->
<overwrite>true</overwrite>
<!--允許移動生成的檔案 -->
<verbose>true</verbose>
</configuration >
</plugin>
3.將generatorConfig.xml檔案放在src/java/resourcess根目錄下
<?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 >
<!--資料庫驅動jar路徑 -->
<classPathEntry location="D:\Repositories\Maven\mysql\mysql-connector-java\5.1.39\mysql-connector-java-5.1.39.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 資料庫連線資訊 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.1.45:3306/cj_test" userId="root" password="[email protected]">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--model生成路徑 -->
<javaModelGenerator targetPackage="shiro.cuijiao.generator.test.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--XML對映檔案,生成的位置(目標包),原始碼資料夾 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--和XML關聯的dao類生成路徑(生成檔名預設是***Mapper.java) -->
<javaClientGenerator type="XMLMAPPER" targetPackage="shiro.cuijiao.generator.test.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--下面是資料庫表名和專案中需要生成類的名稱,建議和資料庫保持一致,如果有多個表,新增多個節點即可 -->
<table schema="public" tableName="dept" domainObjectName="Dept" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
</table>
<table schema="public" tableName="emp" domainObjectName="Emp" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
</table>
</context>
</generatorConfiguration>
4.執行run as:maven build在goals中輸入mybatis-generator:generate
5.重新整理專案,即可看到dao、model、mapper包下自動生成的程式碼
很智慧,根據資料庫生成實體類和對映檔案,型別只能匹配,尤其在庫表比較多的時候,節約了我們的時間。
注:注意版本要對,jdk1.8等