Mybatis-Generator

前言

Mybatis屬於半自動ORM,在使用這個框架中,工作量最大的就是書寫Mapping的映射文件,由於手動書寫很容易出錯,我們可以利用Mybatis-Generator來幫我們自動生成文件。
 

一、使用命令行

1、相關文件
關於Mybatis-Generator的下載可以到這個地址:https://github.com/mybatis/generator/releases
由於我使用的是Mysql數據庫,這裏需要再準備一個連接mysql數據庫的驅動jar包
以下是相關文件截圖:
在這裏插入圖片描述
和Hibernate逆向生成一樣,這裏也需要一個配置文件:

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>
    <!--數據庫驅動-->
    <classPathEntry    location="mysql-connector-java-5.1.34.jar"/>
    <context id="MysqlTables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--數據庫鏈接地址賬號密碼-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/hui" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model類存放位置-->
        <javaModelGenerator targetPackage="com.model" targetProject="src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.mapping" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao類存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.dao" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成對應表及類名-->
        <table tableName="xiaoqiang" domainObjectName="Xiaoqiang" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

需要修改文件配置的地方我都已經把註釋標註出來了,這裏的相關路徑(如數據庫驅動包,生成對應的相關文件位置可以自定義)不能帶有中文。
上面配置文件中的:

<table tableName="xiaoqiang" domainObjectName="Xiaoqiang" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

tableName和domainObjectName爲必選項,分別代表數據庫表名和生成的實體類名,其餘的可以自定義去選擇(一般情況下均爲false)。

生成語句:

java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite

2、使用方法
在該目錄按住Shift鍵,右鍵鼠標選擇"在此處打開命令窗口",複製粘貼生成語句命令即可。

看下效果圖:
首先這個是我的數據庫表
在這裏插入圖片描述
在這裏插入圖片描述
生成的相關代碼:
Xiaoqiang.java:

package com.model;

public class Xiaoqiang {
    private Integer id;

    private String title;

    private String describe;

    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    public String getDescribe() {
        return describe;
    }

    public void setDescribe(String describe) {
        this.describe = describe == null ? null : describe.trim();
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }
}

XiaoqiangMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.XiaoqiangMapper">
  <resultMap id="BaseResultMap" type="com.model.Xiaoqiang">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="title" jdbcType="VARCHAR" property="title" />
    <result column="describe" jdbcType="VARCHAR" property="describe" />
    <result column="content" jdbcType="VARCHAR" property="content" />
  </resultMap>
  <sql id="Base_Column_List">
    id, title, describe, content
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from xiaoqiang
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from xiaoqiang
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.model.Xiaoqiang">
    insert into xiaoqiang (id, title, describe, 
      content)
    values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{describe,jdbcType=VARCHAR}, 
      #{content,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.model.Xiaoqiang">
    insert into xiaoqiang
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="title != null">
        title,
      </if>
      <if test="describe != null">
        describe,
      </if>
      <if test="content != null">
        content,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="title != null">
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="describe != null">
        #{describe,jdbcType=VARCHAR},
      </if>
      <if test="content != null">
        #{content,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.model.Xiaoqiang">
    update xiaoqiang
    <set>
      <if test="title != null">
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="describe != null">
        describe = #{describe,jdbcType=VARCHAR},
      </if>
      <if test="content != null">
        content = #{content,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.model.Xiaoqiang">
    update xiaoqiang
    set title = #{title,jdbcType=VARCHAR},
      describe = #{describe,jdbcType=VARCHAR},
      content = #{content,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

XiaoqiangMapper.java:

package com.dao;

import com.model.Xiaoqiang;

public interface XiaoqiangMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Xiaoqiang record);

    int insertSelective(Xiaoqiang record);

    Xiaoqiang selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Xiaoqiang record);

    int updateByPrimaryKey(Xiaoqiang record);
}

 

二、通過Main方法執行配置文件。

1.創建本文我們將使用的工程Mybatis3,工程結構圖如下:
在這裏插入圖片描述
2.修改jdbc.properties文件,具體內容如下:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hui
jdbc.username=root
jdbc.password=root

3.修改log4j.properties,具體內容如下:

log4j.rootLogger=debug,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4.修改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>
    <properties resource="jdbc.properties" />
    <context id="MysqlTables" targetRuntime="MyBatis3">
        <!-- 生成的pojo,將implements Serializable-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>    
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />    
        </commentGenerator>
    
        <!-- 數據庫鏈接URL、用戶名、密碼 -->
        <jdbcConnection driverClass="${jdbc.driverClassName}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
        </jdbcConnection>
    
        <!--
        默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer
            true,把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal
        -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
    
        <!--
        生成model模型,對應的包路徑,以及文件存放路徑(targetProject),targetProject可以指定具體的路徑,如./src/main/java,    
        也可以使用“MAVEN”來自動生成,這樣生成的代碼會在target/generatord-source目錄下
        -->
        <!--<javaModelGenerator targetPackage="com.hui.test.pojo" targetProject="MAVEN">-->    
        <javaModelGenerator targetPackage="com.hui.entity" targetProject="./src/main/java">    
            <property name="enableSubPackages" value="true"/>
            <!-- 從數據庫返回的值被清理前後的空格  -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
    
        <!--對應的mapper.xml文件  -->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
    
        <!-- 對應的Mapper接口類文件 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hui.dao" targetProject="./src/main/java">    
            <property name="enableSubPackages" value="true"/>    
        </javaClientGenerator>    
    
    
        <!-- 列出要生成代碼的所有表,這裏配置的是不生成Example文件 -->    
        <table tableName="xiaoqiang" domainObjectName="Xiaoqiang"    
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"    
               enableSelectByExample="false" selectByExampleQueryId="false" >    
            <property name="useActualColumnNames" value="false"/>    
        </table>    
    </context>    
</generatorConfiguration>

5.修改GenMain.java文件,具體內容如下:

package com.hui.main;

import java.io.File;  
import java.io.IOException;  
import java.sql.SQLException;  
import java.util.ArrayList;  
import java.util.List;  
  
import org.mybatis.generator.api.MyBatisGenerator;  
import org.mybatis.generator.config.Configuration;  
import org.mybatis.generator.config.xml.ConfigurationParser;  
import org.mybatis.generator.exception.InvalidConfigurationException;  
import org.mybatis.generator.exception.XMLParserException;  
import org.mybatis.generator.internal.DefaultShellCallback;  
  
public class GenMain {  
    public static void main(String[] args) {  
        List<String> warnings = new ArrayList<String>();  
        boolean overwrite = true;  
        String genCfg = "/generatorConfig.xml";  
        File configFile = new File(GenMain.class.getResource(genCfg).getFile());  
        ConfigurationParser cp = new ConfigurationParser(warnings);  
        Configuration config = null;  
        try {  
            config = cp.parseConfiguration(configFile);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (XMLParserException e) {  
            e.printStackTrace();  
        }  
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);  
        MyBatisGenerator myBatisGenerator = null;  
        try {  
            myBatisGenerator = new MyBatisGenerator(config, callback, warnings);  
        } catch (InvalidConfigurationException e) {  
            e.printStackTrace();  
        }  
        try {  
            myBatisGenerator.generate(null);  
        } catch (SQLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
    }  
}

6.修改pom.xml文件,具體內容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hui</groupId>
	<artifactId>Mybatis3</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Mybatis Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<dependencies>
        <dependency>  
            <groupId>org.mybatis.generator</groupId>  
            <artifactId>mybatis-generator-core</artifactId>  
            <version>1.3.5</version>  
        </dependency>

<!-- 		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.1</version>
		</dependency> -->

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

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>Mybatis3</finalName>
	</build>
</project>

7.測試方法:
運行main方法,然後刷新工程即可。正常情況下:控制檯能夠看到如下輸出,刷新工程後項目列表也能夠看到填充文件的變化。

DEBUG [main] - Retrieving column information for table "xiaoqiang"
DEBUG [main] - Found column "id", data type 4, in table "hui..xiaoqiang"
DEBUG [main] - Found column "title", data type 12, in table "hui..xiaoqiang"
DEBUG [main] - Found column "describe", data type 12, in table "hui..xiaoqiang"
DEBUG [main] - Found column "content", data type 12, in table "hui..xiaoqiang"

在這裏插入圖片描述
 

三、通過Maven插件運行。

上面我們的工程是通過maven構建的,mybatis generator中也包含了一個可以集成到Maven的插件,具體做法如下:
1.工程可簡化至:
在這裏插入圖片描述
2.修改pom.xml文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hui</groupId>
	<artifactId>Mybatis3</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Mybatis Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<build>  
        <plugins>  
            <plugin>  
                <groupId>org.mybatis.generator</groupId>  
                <artifactId>mybatis-generator-maven-plugin</artifactId>  
                <version>1.3.5</version>  
                <configuration>  
                    <verbose>true</verbose>  
                    <overwrite>true</overwrite>  
                </configuration>  
            </plugin>  
        </plugins>  
    </build>
</project>

3.在默認情況下,mybatis generator的配置文件的名稱爲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>
	<classPathEntry
		location="C:/Users/Administrator/Desktop/mybatis-generator-1.3.5/mysql-connector-java-5.1.34.jar" />
	<context id="MysqlTables" targetRuntime="MyBatis3">
		<!-- 生成的pojo,將implements Serializable -->
		<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
		<commentGenerator>
			<!-- 是否去除自動生成的註釋 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>

		<!-- 數據庫鏈接URL、用戶名、密碼 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://127.0.0.1:3306/hui" userId="root"
			password="root">
		</jdbcConnection>

		<!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer true,把JDBC DECIMAL 和 
			NUMERIC 類型解析爲java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- 生成model模型,對應的包路徑,以及文件存放路徑(targetProject),targetProject可以指定具體的路徑,如./src/main/java, 
			也可以使用“MAVEN”來自動生成,這樣生成的代碼會在target/generatord-source目錄下 -->
		<!--<javaModelGenerator targetPackage="com.hui.test.pojo" targetProject="MAVEN"> -->
		<javaModelGenerator targetPackage="com.hui.entity"
			targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
			<!-- 從數據庫返回的值被清理前後的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!--對應的mapper.xml文件 -->
		<sqlMapGenerator targetPackage="mappers"
			targetProject="./src/main/resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<!-- 對應的Mapper接口類文件 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.hui.dao" targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>

		<!-- 列出要生成代碼的所有表,這裏配置的是不生成Example文件 -->
		<table tableName="xiaoqiang" domainObjectName="Xiaoqiang"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false">
			<property name="useActualColumnNames" value="false" />
		</table>
	</context>
</generatorConfiguration>

4.運行方法:
在eclipse中,選擇pom.xml文件,擊右鍵先擇Run AS——>Maven Build… ——>在Goals框中輸入:mybatis-generator:generate

最後,在給出一個小建議:在建表時,字段名稱建議用"_"分隔多個單詞,比如:AWB_NO、REC_ID…,這樣生成的entity,屬性名稱就會變成漂亮的駝峯命名,即:awbNo、recId
 

四、解決mybatis-generator無法生成除insert外的方法的問題

mybatis框架提供了非常好用的逆向工程插件,但是在使用過程中會有很多問題。
我在使用中就遇到了只生成insert和insertSeletive方法,而不生成其他根據primary key查詢更新刪除的方法。

解決方案:
1.檢查數據庫中的表是否有主鍵,如果沒有主鍵是不會生成類似selectByPrimaryKey之類的方法的。
2.檢查generatorConfig.xml配置文件中的table標籤是否把這些屬性設爲了false,默認是true,如果設爲了false則無法生成。

enableSelectByPrimaryKey="true"
enableUpdateByPrimaryKey="true"
enableDeleteByPrimaryKey="true"

3.如果使用的mysql驅動是6.x的,那就無法生成,使用5.x版本的就可以生成。(這個比較坑)

參考:
http://www.cnblogs.com/lichenwei/p/4145696.html
http://www.cnblogs.com/wangkeai/p/6934683.html
https://blog.csdn.net/l_bestcoder/article/details/77529285

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章