MyBatis逆向工程

一、加入插件

pom.xml中加入mybatis 代碼自動生成插件

<!--Mybatis逆向工程插件-->
<plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.6</version>
     <configuration>
         <!--配置文件的位置-->
         <configurationFile>GeneratorMapper.xml</configurationFile>
         <verbose>true</verbose>
         <overwrite>true</overwrite>
     </configuration>
 </plugin>

二、GeneratorMapper.xml配置

重要的步驟:

  1. 指定JDBC驅動的jar包位置
  2. 配置數據庫四要素:驅動,url,用戶名,密碼
  3. 指定生成實體類的位置(工程名與包名)
  4. 指定生成的Mapper.xml文件的位置
  5. 指定生成的Mapper接口的位置
  6. 指定數據庫表名及對應的 Java 模型類名(需要生成哪些表)
<?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>
    <!-- 指定連接數據庫的 JDBC 驅動包所在位置,指定到你本機的完整路徑 -->
    <classPathEntry location="H:\PowerNode\jar\MySql\mysql-connector-java-5.1.47.jar"/>
    
    <!-- 配置 table 表信息內容體, targetRuntime 指定採用 MyBatis3 的版本 -->
    <context id="tables" targetRuntime="MyBatis3">
    
        <!-- 抑制生成註釋,由於生成的註釋都是英文的,可以不讓它生成 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        
        <!-- 配置數據庫連接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/springboot"
                        userId="root"
                        password="123">
        </jdbcConnection>
        
        <!-- 生成 model 類, targetPackage 指定 model 類的包名, 
        targetProject 指定生成的 model 放在 eclipse 的哪個工程下面-->
        <javaModelGenerator targetPackage="com.wkcto.springboot.model"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="false" />
        </javaModelGenerator>
        
        <!-- 生成 MyBatis 的 Mapper.xml 文件, 
        targetPackage 指定 mapper.xml 文件的包名, 
        targetProject 指定生成的 mapper.xml 放在 eclipse 的哪個工程下面 -->
        <sqlMapGenerator targetPackage="com.wkcto.springboot.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        
        <!-- 生成 MyBatis 的 Mapper 接口類文件,targetPackage 指定 Mapper 接口類的包名, 
        targetProject 指定生成的 Mapper 接口放在 eclipse 的哪個工程下面 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wkcto.springboot.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        
        <!-- 數據庫表名及對應的 Java 模型類名 -->
        <table tableName="t_student" domainObjectName="Student"
               enableCountByExample="false"
               enableUpdateByExample="false"
        	   enableDeleteByExample="false"
               enableSelectByExample="false"
        	   selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

注意:如果使用高版本, 驅動類變爲: com.mysql.cj.jdbc.Driver,url 後面應該加屬性 nullCatalogMeansCurrent=true,否則生成有問題
當前版本 MySQL 數據庫爲 5.7.18

三、運行插件

在IDEA右側maven中對應的模塊運行插件
在這裏插入圖片描述

四、生成的文件說明

1. mapper接口

MyBatis 只能自動生成單表中的sql語句,所以生成了六個單表操作的基本方法:

package com.wkcto.springboot.mapper;

import com.wkcto.springboot.model.Student;

public interface StudentMapper {
	//根據主鍵進行刪除
    int deleteByPrimaryKey(Integer id);
	//新增所有屬性
    int insert(Student record);
	//新增不爲null的屬性
    int insertSelective(Student record);
	//要把主鍵查詢
    Student selectByPrimaryKey(Integer id);
	//根據主鍵更新不爲null的屬性
    int updateByPrimaryKeySelective(Student record);
	//根據主鍵更新所有屬性
    int updateByPrimaryKey(Student record);
}

2. mapper.xml

除了生成mapper接口中對應的方法,還有sql片段和resultMap
不懂的請戳這裏:MyBatis學習記錄(3)之動態SQL

<mapper> 標籤是將數據庫表中的字段與實體類中的字段一對應起來,MyBatis 推薦數據庫中字段多個單詞使用下劃線"_"隔開,而java中的字段使用的是用駝峯命名法,所以逆向工程會生成<mapper>標籤來管理表字段與實體類之間的映射關係

<?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.wkcto.springboot.mapper.StudentMapper">

    <resultMap id="BaseResultMap" type="com.wkcto.springboot.model.Student">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
    </resultMap>

    <sql id="Base_Column_List">
    	id, name, age
    </sql>

    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from t_student
        where id = #{id,jdbcType=INTEGER}
    </select>
    
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
	    delete from t_student
	    where id = #{id,jdbcType=INTEGER}
    </delete>
  
    <insert id="insert" parameterType="com.wkcto.springboot.model.Student">
	    insert into t_student (id, name, age
	      )
	    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
	      )
    </insert>
    <insert id="insertSelective" parameterType="com.wkcto.springboot.model.Student">
        insert into t_student
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                name,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    
    <update id="updateByPrimaryKeySelective" parameterType="com.wkcto.springboot.model.Student">
        update t_student
        <set>
            <if test="name != null">
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    
    <update id="updateByPrimaryKey" parameterType="com.wkcto.springboot.model.Student">
	    update t_student
	    set name = #{name,jdbcType=VARCHAR},
	      age = #{age,jdbcType=INTEGER}
	    where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>

3. 實體bean

生成的主要是表中字段對應的實體類屬性及對應的Getter和Setter

package com.wkcto.springboot.model;

public class Student {
    private Integer id;

    private String name;

    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

五、細節

1. 進行逆向工程時文件已經存在

進行逆向工程,如果mapper.xml文件已經存在,則會往後面繼續追加,如果mapper.xml文件中已追加的多次,則在啓動服務時會報 BuilderException 異常和 IllegalArgumentException 異常,所以在運行逆向工程的時候,要先刪掉mapper.xml文件再執行逆向工程。

mapper 接口和實體bean 在逆向工程時如果存在會覆蓋之前的

2. 逆向工程時引入工程中其它模塊

進行逆向工程時,如果引用了本包中的模塊,需要先將被引用模塊打包併發布到本地倉庫,否則會報下面的錯:

Failed to execute goal on project 021-springboot-provider: Could not resolve dependencies for project com.wkcto.springboot:021-springboot-provider:jar:1.0.0: Failure to find com.wkcto.springboot:020-springboot-dubbo-interface:jar:1.0.0 in https://maven.aliyun.com/repository/public was cached in the local repository, resolution will not be reattempted until the update interval of aliyunmaven has elapsed or updates are forced -> [Help 1]

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