1. 程式人生 > >IDEA下mybatis逆向工程工具和坑點

IDEA下mybatis逆向工程工具和坑點

mybatis逆向工程:使用mybatis generator外掛,將資料庫表自動生成Bean,mapper,dao檔案,幫你剩下大把時光,但其中有很多坑點,這裡也記錄下來。

1. 首先在pom.xml檔案下加外掛的配置

<build>
	<plugins>
		<!-- mybatis逆向工程外掛 -->
		<plugin>
		<groupId>org.mybatis.generator</groupId>
		<artifactId>mybatis-generator-maven-plugin</artifactId>
		<version>1.3.4</version>
		</plugin>
	</plugins>
</build>

2. 然後繼續在pom.xml新增依賴

<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>5.1.30</version>
			</dependency>

3. 接著建立一個數據庫表(下面按照這個資料庫表做實驗好了)

create table tbl_student
(
  stu_id   int          not null
    primary key,
  stu_name varchar(255) not null,
  chinese  int          not null,
  math     int          not null,
  english  int          not null
);

4. 建立如下一個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>
<classPathEntry location="H:\mashen\TOOL\maven\apache-maven-3.5.0\resp\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar"/>
  <context id="context1">
  
  <!-- 1.關閉自動生成註釋(給生成檔案的註釋太多了,影響讀程式) -->
  <commentGenerator>
  <property name="suppressAllComments" value="true"/>
  </commentGenerator>
  
  <!-- 2.連線資料庫 -->
    <jdbcConnection
    connectionURL="jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&amp;useSSL=true"
    driverClass="com.mysql.jdbc.Driver"
    userId="root"
    password="123"
    />
    
    <!-- 3.指定javabean生成位置 -->
    <javaModelGenerator targetPackage="com.suguowen.bean" targetProject="./src/main/java" />

    <!-- 4.指定sql.mapper對映檔案生成位置 -->
    <sqlMapGenerator targetPackage="com.suguowen.dao.mapper" targetProject="./src/main/resources" />
    
    <!-- 5.指定sql.interface介面生成位置 -->
    <javaClientGenerator targetPackage="com.suguowen.dao" targetProject="./src/main/java" type="XMLMAPPER" />
    
    <!-- 6.table指定生成策略 -->
    <table tableName="tbl_student" domainObjectName="Student">
    </table>

  </context>
</generatorConfiguration>

5.分析上面的表,分成三部分

第一部分,是連線資料庫,坑點是URL後面的引數,多個引數用'&'會提示符號錯誤,要用'&amp',然後這兩個引數雖然不知道上面意思,但是不配有時候會報錯,所以加上吧

第二部分,是指定自動生成的檔案的路徑,targetProject是新建專案的固定路徑,targetPackage是基於專案路徑自己手動新增的路徑,坑點是targetProject配置./src這裡的'.'我寫專案名大小寫都試過,都錯了,不知道為什麼,然後機智的寫'.'避開了坑

6. 接著開啟maven project裡一開始安裝好的外掛,雙擊就會執行

7. 檔案生成的結果(有顏色是因為我專案放github了,修改顯示不同顏色~~)