關於Mybatis逆向工程的一些理解和總結

在Java中,優秀的框架一般都離不開反射的使用,有時候自己在爲了實現或者簡化某些功能或者操作時,自己也可以開發一些小型框架。在學習Mybatis框架時,會接觸到很多關於反射的東西,當然如果你有興趣打開源碼瀏覽的話。今天就是想無聊,談談Mybatis的逆向工程。

說起Mybatis這個框架,我們基本會用到的幾個東西,用一張草圖來稍微描述一下:

對於這張圖大家一定都不陌生,而且我們知道,這四個東西聯繫都非常緊密。比如通過數據庫表我們能知道pojo類相應的屬性,通過mapper接口,我們能知道mapper配置文件中的SQL語句以及其輸入輸出參數的定義等等。 而對於mapper配置文件,則可以看做是其他三者的橋樑。所以Mybatis設計了逆向工程,利用逆向工程,我們可以利用其中的某一個來生成我們所需要的其他全部文件或者配置。

接下來,實現一個簡單的逆向工程,利用一個數據庫表,生成所需的(配置)文件。

關於數據庫和數據庫表,我本機爲了測試已經建立好了,如下圖:

接下來就是開始逆向工程,需要準備的jar包除了我們日常使用mybatis所用到的之外,還需要一個mybatis-generator-core-1.3.5.jar,可以到maven庫裏面去下載。配置好jar包後,我們需要開始配置逆向工程,首先建立逆向工程配置文件:generator.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>
   <context id="charlesTests" targetRuntime="MyBatis3">
   <commentGenerator>
   <!--
			suppressAllComments屬性值:
				true:自動生成實體類、SQL映射文件時沒有註釋
				true:自動生成實體類、SQL映射文件,並附有註釋
		  -->
  <property name="suppressAllComments" value="true" />
 </commentGenerator>
 
 
 <!-- 數據庫連接信息 -->
  <jdbcConnection driverClass="com.mysql.jdbc.Driver"
   connectionURL="jdbc:mysql://localhost:3306/student" 
   userId="root"  password="charles">
  </jdbcConnection>
	  <!-- 
				forceBigDecimals屬性值: 
					true:把數據表中的DECIMAL和NUMERIC類型,
	解析爲JAVA代碼中的java.math.BigDecimal類型 
					false(默認):把數據表中的DECIMAL和NUMERIC類型,
	解析爲解析爲JAVA代碼中的Integer類型 
			-->
 <javaTypeResolver>
  	<property name="forceBigDecimals" value="false" />
 </javaTypeResolver>
 <!-- 
		targetProject屬性值:實體類的生成位置  
		targetPackage屬性值:實體類所在包的路徑
	-->
 <javaModelGenerator targetPackage="com.charles.entity"
                            targetProject=".\src">
  <!-- trimStrings屬性值:
			true:對數據庫的查詢結果進行trim操作
			false(默認):不進行trim操作       
		  -->
  <property name="trimStrings" value="true" />
 </javaModelGenerator>
 <!-- 
		targetProject屬性值:SQL映射文件的生成位置  
		targetPackage屬性值:SQL映射文件所在包的路徑
	-->
  <sqlMapGenerator targetPackage="com.charles.mapper" 
			targetProject=".\src">
  </sqlMapGenerator>
  <!-- 生成動態代理的接口  -->
 <javaClientGenerator type="XMLMAPPER" targetPackage="com.charles.mapper" targetProject=".\src">
 </javaClientGenerator>
 
 <!-- 指定數據庫表  -->
  <table tableName="info"> </table>
 </context>
</generatorConfiguration>

關於配置文件中的配置屬性,這裏就不再細說,代碼裏已有註釋。

接下來,我們就可以建立測試類來完成逆向工程的開發,新建Java源文件Test.java,代碼如下:

package com.charles.tests;

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 Test {
	public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException
 {
//    本四行代碼爲填參數而生
		List<String> warnings = new ArrayList<>();
		ConfigurationParser cp=new ConfigurationParser(warnings);
                Configuration config=cp.parseConfiguration(new File("src/generator.xml"));
		DefaultShellCallback callBack = new DefaultShellCallback(true);
		


//		逆向工程的核心類
		MyBatisGenerator generator=new MyBatisGenerator(config, callBack , warnings);
		generator.generate(null);
		
	}
}

測試類建立完畢,這裏稍稍提一下,其實關鍵代碼知識最後兩句,前面四行代碼只是爲了給倒數第二行代碼提供參數,對於第一行,就是把相關的警告信息放在該集合中;第二行是爲了第三行config對象的產生而新建的對象。後面兩者就不說了,按照相應的提示就能完成。至此,我們所需的準備工作已經做完,此時的項目結構如下:

我們運行該程序,然後刷新項目目錄,發現:

新增了兩個包,以及包裏面有相關的類,點擊查看:info.java

package com.charles.entity;

public class Info {
    private String name;

    private Integer id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getId() {
        return id;
    }

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

典型的pojo,與我們數據庫的字段一一對應。再觀察infoMapper.java

package com.charles.mapper;

import com.charles.entity.Info;
import com.charles.entity.InfoExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface InfoMapper {
    long countByExample(InfoExample example);

    int deleteByExample(InfoExample example);

    int insert(Info record);

    int insertSelective(Info record);

    List<Info> selectByExample(InfoExample example);

    int updateByExampleSelective(@Param("record") Info record, @Param("example") InfoExample example);

    int updateByExample(@Param("record") Info record, @Param("example") InfoExample example);
}

與之對應的infoMapper.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.charles.mapper.InfoMapper">
  <resultMap id="BaseResultMap" type="com.charles.entity.Info">
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="id" jdbcType="INTEGER" property="id" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    name, id
  </sql>
  <select id="selectByExample" parameterType="com.charles.entity.InfoExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from info
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <delete id="deleteByExample" parameterType="com.charles.entity.InfoExample">
    delete from info
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.charles.entity.Info">
    insert into info (name, id)
    values (#{name,jdbcType=VARCHAR}, #{id,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.charles.entity.Info">
    insert into info
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        name,
      </if>
      <if test="id != null">
        id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.charles.entity.InfoExample" resultType="java.lang.Long">
    select count(*) from info
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update info
    <set>
      <if test="record.name != null">
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update info
    set name = #{record.name,jdbcType=VARCHAR},
      id = #{record.id,jdbcType=INTEGER}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <resultMap id="BaseResultMap" type="com.charles.entity.Info">
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="id" jdbcType="INTEGER" property="id" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    name, id
  </sql>
  <select id="selectByExample" parameterType="com.charles.entity.InfoExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from info
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <delete id="deleteByExample" parameterType="com.charles.entity.InfoExample">
    delete from info
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.charles.entity.Info">
    insert into info (name, id)
    values (#{name,jdbcType=VARCHAR}, #{id,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.charles.entity.Info">
    insert into info
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        name,
      </if>
      <if test="id != null">
        id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.charles.entity.InfoExample" resultType="java.lang.Long">
    select count(*) from info
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update info
    <set>
      <if test="record.name != null">
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update info
    set name = #{record.name,jdbcType=VARCHAR},
      id = #{record.id,jdbcType=INTEGER}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
</mapper>

一套完整而又官方增刪改查的mapper配置文件來了;

至此,已經基本完成了一個逆向工程的例子,但是在實際的開發中,這種關於逆向開發的應用是不常見的,其原因之一就是生成的文件很規整而又官方,對於不同風格的程序員來說,可能會有困擾;當然,這個項目中還有兩個以example結束的文件,這個是關於一些使用的說明,用不上,可以刪除不用。

 

 

 

 

 

 

 

 

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