MybatisCodehelperPro插件 一鍵生成join查詢

當(dāng)我們使用從數(shù)據(jù)庫(kù)生成crud時(shí),只能生成單表操作的sql
如果兩張表 有關(guān)聯(lián)關(guān)系 我們?cè)趺磥碜鲎詣?dòng)生成 并且能滿足以下條件

  1. 兩張表有相同的字段 也能生成
  2. 在表中添加或減少字段后 關(guān)聯(lián)的字段也能增加和減少
  3. 生成接口方法 和 resultMap 用戶只需要加參數(shù) 和關(guān)聯(lián)條件就行

我們可以先觀察下 數(shù)據(jù)庫(kù)生成crud生成的代碼

 <resultMap id="BaseResultMap" type="com.codehelper.domain.A">
    <!--@mbg.generated-->
    <id column="id" property="id" />
    <result column="user_id" property="userId" />
    <result column="delete" property="delete" />
    <result column="mydate" property="mydate" />
  </resultMap>
  <sql id="Base_Column_List">
    <!--@mbg.generated-->
    id, user_id, `delete`, mydate
  </sql>

會(huì)有一個(gè)BaseResultMap和一個(gè)BaseColumnList兩個(gè)塊 這個(gè)BaseResultMap和BaseColumnList在表字段變了后 也會(huì)相應(yīng)變化
在mybatis的xml中 我們可以引用其他xml定義的resultMap和sql塊
我們寫一個(gè)join的sql 可以是

 select
    <include refid="Base_Column_List" />,<include refid="com.codehelper.mapper.BMapper.Base_Column_List"/>
    from a join b on b.a_id = a.id

但是如果兩張表有相同的字段的話 就會(huì)用不了

字段沖突了 我們可以在字段前加一個(gè)表名 即下面這種

<sql id="Join_Column_List">
    <!--@mbg.generated-->
    a.id as a_id,
    a.user_id as a_user_id,
    a.delete as a_delete,
    a.mydate as a_mydate
  </sql>
  <resultMap id="JoinResultMap" type="com.codehelper.domain.A">
    <!--@mbg.generated-->
    <id column="a_id" property="id"/>
    <result column="a_user_id" property="userId"/>
    <result column="a_delete" property="delete"/>
    <result column="a_mydate" property="mydate"/>
  </resultMap>

在前面加一個(gè)前綴 就不會(huì)有沖突了

這時(shí)我們可以寫出sql

 <select id="AJoinB" resultMap="selectJoin">
    select<include refid="Join_Column_List"/>,
    <include refid="com.codehelper.mapper.BMapper.Join_Column_List"/>
    from a join b on 
  </select>

對(duì)于兩張表關(guān)聯(lián) 可能是一對(duì)一 或者一對(duì)多

我們也可以生成好實(shí)體類 如果是 一對(duì)一的話 生成類為

public class AWithB extends A {
    private B b;
    public B getB() {
        return b;
    }
    public void setB(B b) {
        this.b = b;
    }
}

xml中的resultMap也可以生成好

  <resultMap id="selectJoin" type="com.codehelper.domain.AWithB" extends="JoinResultMap">
    <association property="b" resultMap="com.codehelper.mapper.BMapper.JoinResultMap"/>
  </resultMap>

接口中的方法也可以自動(dòng)生成好

List<AWithB> AJoinB();

對(duì)于 生成 的 join_column_list 和 joinResultMap 都在當(dāng)前表的范圍內(nèi)
當(dāng)用戶在表重新生成crud時(shí) 我們可以檢測(cè)當(dāng)前表是否存在 joinColumnList這個(gè) 如果有就給更新掉
這樣可以保證在表添加修改減少字段時(shí) 都能更新掉

在這個(gè)生成之后 我們添加一下參數(shù) 和關(guān)聯(lián)關(guān)系 就可以直接使用了

在xml文件上 右鍵選擇 generateJoin 即可

最終生成截圖


一鍵生成兩張表關(guān)聯(lián)的join.gif

使用該功能生成目前有一個(gè)要求 兩個(gè)xml 中需要有BaseResultMap存在 并且要有一個(gè)insert語句 這樣我可以找到表名
以后會(huì)優(yōu)化下

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容