Mybatis - association 分步查詢。

  • 場(chǎng)景
    在實(shí)際的開發(fā)過程中,往往會(huì)從多個(gè)表里獲取數(shù)據(jù)。此時(shí)需要用到多表操作。如查詢用戶的個(gè)人信息及部門信息。

  • 實(shí)例
    UserMapper.java

public interface UserMapper {
  UserInfo getUserInfoById (Integer id);
}

DepartmentMapper.java

public interface DepartmentMapper {
  Department getDepartmentByUserId (Integer uid);
}

UserMapper.xml

<select id="getUserInfo" resultMap="userInfoMap">
  SELECT username, age, workno, deptid
  FROM user WHERE uid = #{id}
</select>

<resultMap id="userInfoMap" type="com.cat.pojo.UserInfo">
  <result column="username" property="uname"/>
  <result column="age" property="age"/>
  <result column="workno" property="workNo"/>
  
  <!-- 將查詢出來的User對(duì)象的deptid傳入,封裝成具體的Department信息,得到用戶的信息及Department信息 -->
  <association property="dept" column="deptid" select="com.cat.mapper.DepartmentMapper.getDepartmentByUserId" />
</resultMap>

DepartmentMapper.xml

<select id="getDepartmentByUserId" parameterType="string" resultType="com.cat.pojo.Department">
  SELECT department_name, leader FROM department WHERE id = #{deptId}
</select>
  • SQL執(zhí)行過程
    此時(shí)數(shù)據(jù)的查詢將會(huì)分為兩步,第一步將用戶檢索出來,第二步再根據(jù)每個(gè)用戶的deptid查詢到部門信息。
最后編輯于
?著作權(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)容