Mybatis學習之自定義映射resultMap(七)

這里寫目錄標題

  • 一、準備工作
    • 1、新建maven工程
    • 2、準備兩張表
    • 3、建立mapper、pojo、映射文件
      • mapper接口
      • pojo
      • xxxMapper.xml
  • 二、resultMap處理字段和屬性的映射關系
    • 1、用起別名的方式保證字段名與屬性名一致
    • 2、逐一設置resultMap映射關系
    • 3、配置mapUnderscoreToCamelCase
  • 三、多對一映射關系
    • 1、級聯方式處理映射關系
    • 2、使用association處理映射關系
    • 3、分布查詢
      • 3.1、查詢員工信息
      • 3.2、根據員工所對應的部門id查詢部門信息
      • 延遲加載
  • 四、一對多映射關系
    • 1、collection
    • 2、分步查詢
      • 1)查詢部門信息
      • 2)根據部門id查詢部門中所有員工
      • 3)測試類

一、準備工作

1、新建maven工程

新建一個maven工程,具體pom.xml文件以及數據庫連接配置文件可以參考之前的筆記。

2、準備兩張表

  • 部門員工表
CREATE TABLE `t_emp` (`eid` int(11) NOT NULL AUTO_INCREMENT,`emp_name` varchar(45) DEFAULT NULL,`age` int(11) DEFAULT NULL,`sex` char(1) DEFAULT NULL,`email` varchar(45) DEFAULT NULL,`did` int(11) DEFAULT NULL,PRIMARY KEY (`eid`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COMMENT='部門員工表';
  • 部門機構表
CREATE TABLE `t_dept` (`did` int(11) NOT NULL AUTO_INCREMENT,`dept_name` varchar(45) DEFAULT NULL,PRIMARY KEY (`did`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='部門機構表';

每個表中添加相關參數:

INSERT INTO demo.t_emp (eid, emp_name, age, sex, email, did) VALUES(1, 'Apple', 22, '女', '123456@qq.com', 1);
INSERT INTO demo.t_emp (eid, emp_name, age, sex, email, did) VALUES(2, 'Bela', 33, '女', '123456@qq.com', 1);
INSERT INTO demo.t_emp (eid, emp_name, age, sex, email, did) VALUES(3, 'Cherry', 21, '女', '123456@qq.com', 2);
INSERT INTO demo.t_emp (eid, emp_name, age, sex, email, did) VALUES(4, 'David', 55, '男', '123456@qq.com', 2);
INSERT INTO demo.t_emp (eid, emp_name, age, sex, email, did) VALUES(5, 'Eve', 25, '男', '123456@qq.com', 3);
INSERT INTO demo.t_emp (eid, emp_name, age, sex, email, did) VALUES(6, 'Feman', 34, '男', '123456@qq.com', 3);INSERT INTO demo.t_dept (did, dept_name) VALUES(1, '財務部');
INSERT INTO demo.t_dept (did, dept_name) VALUES(2, '倉儲部');
INSERT INTO demo.t_dept (did, dept_name) VALUES(3, '技術部');

3、建立mapper、pojo、映射文件

在這里插入圖片描述

mapper接口

public interface EmpMapper {
}
public interface DeptMapper {
}

pojo

Dept pojo:

public class Dept {private Integer did;private String deptName;@Overridepublic String toString() {return "Dept{" +"did=" + did +", deptName='" + deptName + '\'' +'}';}public Integer getDid() {return did;}public void setDid(Integer did) {this.did = did;}public String getDeptName() {return deptName;}public void setDeptName(String deptName) {this.deptName = deptName;}public Dept() {}public Dept(Integer did, String deptName) {this.did = did;this.deptName = deptName;}}

Emp pojo :

public class Emp {private Integer eid;private String empName;private Integer age;private String sex;private String email;public Emp() {}public Emp(Integer eid, String empName, Integer age, String sex, String email) {this.eid = eid;this.empName = empName;this.age = age;this.sex = sex;this.email = email;}@Overridepublic String toString() {return "Emp{" +"eid=" + eid +", empName='" + empName + '\'' +", age=" + age +", sex='" + sex + '\'' +", email='" + email + '\'' +'}';}public Integer getEid() {return eid;}public void setEid(Integer eid) {this.eid = eid;}public String getEmpName() {return empName;}public void setEmpName(String empName) {this.empName = empName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}

xxxMapper.xml

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo.mybatis.mapper.DeptMapper"></mapper>

EmpMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo.mybatis.mapper.EmpMapper"></mapper>

二、resultMap處理字段和屬性的映射關系

若字段名和實體類中的屬性名不一致,但是數據庫字段名符合數據庫的規則(使用_),實體類中的屬性名符合Java的規則(使用駝峰)。
這時候可以通過兩種方式處理字段名和實體類中的屬性的映射關系:

  • 可以通過為字段起別名的方式,保證和實體類中的屬性名保持一致
  • 逐一設置resultMap映射關系
  • 可以在MyBatis的核心配置文件中設置一個全局配置信息mapUnderscoreToCamelCase,可以在查詢表中數據時,自動將_類型的字段名轉為駝峰。

1、用起別名的方式保證字段名與屬性名一致

和sql中一樣,用字段名 屬性名 如(emp_name empName)來使二者一致。
在mybatic-config.xml文件中添加別名配置:

    <typeAliases><typeAlias type="cn.demo.mybatis.pojo.Emp" alias="Emp"></typeAlias></typeAliases>
 <!--    List<Emp> getAllEmp();--><select id="getAllEmp" resultType="Emp">select eid, emp_name empName, age, sex, email from t_emp</select>

2、逐一設置resultMap映射關系

在resultMap中,一一對應的設置屬性名—>字段名,再在select標簽中添加resultMap=“對應resultMap的id”

    <resultMap id="empResultMap" type="cn.demo.mybatis.pojo.Dept"><id property="did" column="did"></id><result property="deptName" column="dept_name"></result></resultMap><select id="getAllDept" resultMap="empResultMap">select * from t_dept</select>

resultMap設置自定義映射關系:
+ id:唯一標識
+ type:映射的實體類型
子標簽:
+ id:設置主鍵的映射關系
+ result:設置其他的映射關系
+ property:設置映射關系中的屬性名,即Java實體類類型的屬性
+ column:設置映射關系中的字段名,必須是sql語句查詢出來的字段名

3、配置mapUnderscoreToCamelCase

在全局配置文件mybatis-config.xml中,加入如下屬性配置信息:

<configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>

這里設置MyBatis的全局配置,將下劃線自動映射成駝峰,比如emp_name -> empName。
注意:settings標簽要放在properties后面,否則會報錯。

三、多對一映射關系

需要查詢一對多,多對一的關系,需要在“一”的pojo中加入多的List<>屬性,在“多”的pojo中加入“一”。
也就是說,在Dept類中,需要加入 private List emps; ,在Emp類中,要加入 private Dept dept 。然后給他們各自添加get、set方法,重寫構造器和toString()。

1、級聯方式處理映射關系

EmpMapper.xml中:

<!--    多對一映射關系,方式一:級聯屬性賦值--><resultMap id="getEmpAndDeptResultMapOne" type="Emp"><id property="eid" column="eid"></id><result property="empName" column="emp_name"></result><result property="age" column="age"></result><result property="sex" column="sex"></result><result property="email" column="email"></result><result property="dept.did" column="did"></result><result property="dept.deptName" column="dept_name"></result></resultMap><!--        Emp getEmpAndDept(@Param("eid") Integer eid);--><select id="getEmpAndDept" resultMap="getEmpAndDeptResultMapOne">select * from t_emp left join t_depton t_emp.eid = t_dept.did WHERE t_emp.eid = #{eid}</select>

EmpMapper類中

public interface EmpMapper {/*** 查詢員工及其所對應的部門信息*/Emp getEmpAndDept(@Param("eid") Integer eid);
}

測試類中:

    @Testpublic void testGetEmpAndDept(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);Emp empAndDept = mapper.getEmpAndDept(3);System.out.println(empAndDept);}

在這里插入圖片描述

2、使用association處理映射關系

當一個對象包含一個關聯對象時(例如:一個員工emp對應一個部門dept),可以使用映射一對一關系。
EmpMapper.xml:

    <resultMap id="empDeptMap" type="Emp"><id column="eid" property="eid"></id><result column="emp_name" property="empName"></result><result column="age" property="age"></result><result column="sex" property="sex"></result><result property="email" column="email"></result><association property="dept" javaType="Dept"><id column="did" property="did"></id><result column="dept_name" property="deptName"></result></association></resultMap><!--Emp getEmpAndDeptByEid(@Param("eid") int eid);--><select id="getEmpAndDeptByEid" resultMap="empDeptMap">select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did = dept.did where emp.eid = #{eid}</select>

association標簽:

  • property:映射實體類屬性名
  • javaType:映射java類型
  • column:映射數據庫字段名
  • jdbcType:映射數據庫類型

3、分布查詢

3.1、查詢員工信息

EmpMapper.xml

    <resultMap id="getEmpAndDeptByStepResultMap" type="Emp"><id property="eid" column="eid"></id><result property="empName" column="emp_name"></result><result property="age" column="age"></result><result property="sex" column="sex"></result><result property="email" column="email"></result><result property="did" column="did"></result><association property="dept"select="cn.demo.mybatis.mapper.DeptMapper.getDeptByStep"column="did"fetchType="eager"></association></resultMap><!--     Emp getEmpByStep(@Param("eid") int eid);--><select id="getEmpByStep" resultMap="getEmpAndDeptByStepResultMap">select * from t_emp where eid = #{eid}</select>
  • select:設置了分布查詢的sql唯一標識(xml的namespace.SQLId或mapper接口的全類名.方法名)
  • column:分步查詢的條件
  • fetchType:通過該屬性手動控制延遲加載的效果;lazy表示延遲加載,eager表示立即加載

3.2、根據員工所對應的部門id查詢部門信息

DeptMapper.xml:

    <!--        Dept getEmpAndDeptByStepTwo(Integer did);--><!--    分步查詢可以實現懶加載--><select id="getDeptByStep" resultType="Dept">select * from t_dept where did = #{did}</select>

延遲加載

分布查詢的優點:可以實現延遲加載,但是必須在核心配置文件中設置全局配置信息:

  • lazyLoadingEnabled:延遲加載的全局開關。當開啟時,所有關聯對象都會延遲加載。
  • aggressiveLazyLoading:當開啟時,任何方法的調用都會加載該對象的所有屬性。否則每個屬性都會按需加載。
    lazyLoadingEnabled是控制是否開啟懶加載的,而aggressiveLazyLoading是控制關聯對象是如何進行懶加載的,比如控制當對關聯對象任何的調用都會完全加載所有屬性,還是只是按需加載對應屬性。
<settings><!--開啟延遲加載--><setting name="lazyLoadingEnabled" value="true"/>
</settings>

特定關聯關系中可通過設置 fetchType 屬性來覆蓋該項的開關狀態
此時就可以實現按需求加載,獲取的數據是什么,就會執行相應的sql。此時可通過association和 collection中的fetchType屬性設置當前的分布查詢是否使用延遲加載,fetchType=“lazy(延遲加 載)|eager(立即加載)”。

通過fetchType參數,可以手動控制延遲加載或立即加載,否則根據全局配置的屬性決定是延遲加載還是立即加載。

    @Testpublic void testGetEmpByStep() throws IOException {SqlSession sqlSession = SqlSessionUtils.getSqlSession();EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);Emp empAndDept = mapper.getEmpByStep(1);//先打印出emp的元素System.out.println(empAndDept.getEmpName());System.out.println("=====================");//再打印出deptSystem.out.println(empAndDept.getDept());}

當延遲開關打開時候,加載如下:
在這里插入圖片描述
當延遲開關關閉時候,加載如下:
在這里插入圖片描述

四、一對多映射關系

根據部門id查找部門以及部門中的員工信息。

1、collection

DeptMapper接口:

	 /*** 獲取部門以及部門中所有的員工信息*/Dept getDeptAndEmp(@Param("did") Integer did);

DeptMapper.xml:

    <resultMap id="deptAndEmpResultMap" type="Dept"><id property="did" column="did"></id><result property="deptName" column="dept_name"></result><!--collection:處理一對多的映射關系ofType:表示該屬性對應的集合中存儲數據的類型--><collection property="emps" ofType="Emp"><id property="eid" column="eid"></id><result property="empName" column="emp_name"></result><result property="age" column="age"></result><result property="sex" column="sex"></result><result property="email" column="email"></result></collection></resultMap><!--        Dept getDeptAndEmp(@Param("did") Integer did);--><select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}</select>

測試類

   @Testpublic void testGetDeptAndEmp(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);Dept dept = mapper.getDeptAndEmp(1);System.out.println(dept);}

注意:
這里要在Dept類中,要加入private List emps;

2、分步查詢

1)查詢部門信息

	Dept getDeptAndEmoByStepOne(@Param("did") Integer did)
<!--    分步查詢-->!--    分步查詢--><resultMap id="deptAndEmoByStepOneMap" type="Dept"><id property="did" column="did"></id><result property="deptName" column="dept_name"></result><collection property="emps"select="cn.demo.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"column="did"></collection></resultMap><!--        Dept getDeptAndEmoByStepOne(@Param("did") Integer did);--><select id="getDeptAndEmoByStepOne" resultMap="deptAndEmoByStepOneMap">select * from t_dept where did = #{did}</select>

2)根據部門id查詢部門中所有員工

List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
<!--    List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);--><select id="getDeptAndEmpByStepTwo" resultType="Emp">select * from t_emp where did = #{did}</select>

3)測試類

    @Testpublic void testGetDeptAndEmpBySteps() throws IOException {SqlSession sqlSession = SqlSessionUtils.getSqlSession();DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);Dept dept = mapper.getDeptAndEmoByStepOne(2);System.out.println(dept.getDeptName());System.out.println("-----****************======分割線=======-----****************");System.out.println(dept);}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/92662.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/92662.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/92662.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數學學習 | 高數、線代、概率論及數理統計薦書

注&#xff1a;本文為 “數學學習書目推薦” 相關合輯。 略作重排&#xff0c;如有內容異常&#xff0c;請看原文。 高等數學、線性代數及概率論與數理統計領域推薦書目 西湖邊的卡夫卡 編輯于 2023-09-19 13:26 7495 人贊同了該回答 數學具有內在的美學屬性&#xff0c;但并非…

【LLM實戰|langgraph】langgrpah基礎

every blog every motto: You can do more than you think. https://blog.csdn.net/weixin_39190382?typeblog 0. 前言 langgraph 基礎 1. Chatbot實現 # !pip install langchain # !pip install langgraphfrom typing import Annotatedfrom typing_extensions import Typ…

大疆無人機使用eport連接Jetson主板實現目標檢測

所需硬件設備如下&#xff1a; 實現原理&#xff1a; 視頻流獲取&#xff1a;從大疆無人機獲取實時視頻流。數據傳輸&#xff1a;將視頻流傳輸至 Jetson 平臺。目標檢測處理&#xff1a;在 Jetson 上運行目標檢測算法對傳入的視頻幀進行分析 EPort開發套件 大疆官網給出了…

Typora激活與使用

Typora下載 下載地址&#xff1a;Typora 官方中文站 Typora&#xff08;1.9.5及其以前的版本&#xff09; 工具&#xff1a;待補充 流程 1.解壓工具 2.將license-gen.exe、node_inject.exe兩個文件放于typora安裝目錄下 3.在typora安裝目錄下運行cmd&#xff08;可以打開…

圖片拆分工具,自定義宮格切割

軟件介紹 今天推薦一款實用的圖像處理工具——lmage Splitter&#xff0c;支持圖像拆分與格式互轉功能&#xff0c;無廣告干擾&#xff0c;操作簡單流暢&#xff0c;滿足多樣化圖片編輯需求。 軟件優勢 該工具為綠色版設計&#xff0c;無需安裝即可直接運行&#xff0c;下載…

23種設計模式解析--創建型模式

創建型模式&#xff08;造物主的智慧&#xff09; 單例模式 模式定義 單例模式&#xff08;Singleton&#xff09;確保一個類僅有一個實例&#xff0c;并提供該實例的全局訪問點。核心思想是通過私有化構造函數和靜態成員實現受控的對象創建。核心實現要點 私有構造函數&#x…

全面解析軟件工程形式化說明技術

一、形式化說明技術概述&#xff1a;從模糊到精確的跨越 在軟件工程的發展歷程中&#xff0c;需求說明技術始終是確保軟件系統成功開發的關鍵環節。從早期依賴自然語言的非形式化描述&#xff0c;到如今基于數學和邏輯的形式化方法&#xff0c;這一領域經歷了從模糊到精確的深…

百度網盤自動啟動如何關閉,關閉智能看圖

#某度軟件引起的奔潰#在日常辦公中&#xff0c;有時候雙擊圖片&#xff0c;會自動打開了某度的網盤&#xff0c;很奇怪莫名其妙的為什么會關閉網盤后又自動打開了。如何發現是某度的牛虻軟件在搞鬼的&#xff1f;我右鍵圖片&#xff0c;選擇打開方式&#xff0c;發現有“智能看…

疏老師-python訓練營-Day40訓練和測試的規范寫法

浙大疏錦行 知識點回顧&#xff1a; 彩色和灰度圖片測試和訓練的規范寫法&#xff1a;封裝在函數中展平操作&#xff1a;除第一個維度batchsize外全部展平dropout操作&#xff1a;訓練階段隨機丟棄神經元&#xff0c;測試階段eval模式關閉dropout 作業&#xff1a;仔細學習下測…

【重磅發布】flutter_chen_keyboard -專注于鍵盤相關功能

flutter_chen_keyboard 一個功能強大且易于使用的 Flutter 鍵盤增強庫&#xff0c;專為提升移動應用的鍵盤交互體驗而設計。 &#x1f4d6; 庫簡介 flutter_chen_keyboard 是一個專注于鍵盤相關功能的 Flutter 工具庫&#xff0c;旨在為開發者提供更流暢、更智能的鍵盤交互解決…

idea設置注釋--帶日期和作者和描述

最終效果 在File Header中添加如下內容&#xff1a; /*** author ${USER}* date ${DATE} ${TIME}* description ${DESCRIPTION}*/${USER}&#xff1a;IDEA 里設置的用戶名 ${DATE}&#xff1a;當前日期 ${TIME}&#xff1a;當前時間 可以加自定義變量&#xff0c;比如 ${DESCRI…

【Linux】Socket編程——UDP版

&#x1f4dd;前言&#xff1a; 這篇文章我們來講講Linux——udpsocket &#x1f3ac;個人簡介&#xff1a;努力學習ing &#x1f4cb;個人專欄&#xff1a;Linux &#x1f380;CSDN主頁 愚潤求學 &#x1f304;其他專欄&#xff1a;C學習筆記&#xff0c;C語言入門基礎&#…

RabbitMQ面試精講 Day 14:Federation插件與數據同步

【RabbitMQ面試精講 Day 14】Federation插件與數據同步 開篇 歡迎來到"RabbitMQ面試精講"系列第14天&#xff0c;今天我們將深入探討RabbitMQ Federation插件與跨集群數據同步機制。在分布式系統架構中&#xff0c;如何實現消息隊列集群間的數據同步是確保業務連續…

AI編程工具 | Trae介紹

描述需求就可以自動創建可運行的完整項目了&#xff0c;確實很強&#xff01; 終端中的報錯信息都可以快速作為上下文輸入&#xff0c;點擊確認就可以自動修改&#xff0c;賊好使&#xff01; Trae 編程工具詳細介紹 一、產品簡介 Trae 是字節跳動于 2025 年 1 月 19 日推出的…

【第11話:感知算法基礎3】目標檢測:深度學習目標檢測模型介紹入門及常用模型詳解

深度學習目標檢測模型介紹入門及常用模型詳解 目標檢測是計算機視覺的核心任務&#xff0c;需同時完成目標定位&#xff08;輸出邊界框坐標&#xff09;和目標分類&#xff08;識別類別&#xff09;。深度學習通過端到端訓練顯著提升了檢測精度和效率&#xff0c;主要分為兩類架…

稿定科技:多云架構下的 AI 存儲挑戰與 JuiceFS 實踐

稿定科技&#xff08;gaoding.com&#xff09;是一家專注于為企業和個人提供視覺內容創新方案的科技公司&#xff0c;致力于打造全新的設計方式&#xff0c;幫助更多用戶輕松掌控設計&#xff0c;創造價值。 隨著 AI 技術的加速發展&#xff0c;數據存儲和管理成為支撐公司創新…

徘徊識別場景誤報率↓77%:陌訊動態時序建模方案實戰解析

原創聲明本文為原創技術解析&#xff0c;核心技術參數與架構設計參考自《陌訊技術白皮書》&#xff0c;轉載請注明來源。一、行業痛點&#xff1a;徘徊識別的現實困境在安防監控領域&#xff0c;徘徊行為識別是保障公共安全的關鍵技術&#xff08;如商場防盜竊、園區防闖入等場…

C# 通過第三方庫INIFileParser管理INI配置文件

C# 通過第三方庫INIFileParser管理INI配置文件目錄前言一、添加動態庫二、添加接口類代碼總結前言 很多時候我們是直接調用系統的C庫中的GetPrivateProfileString和WritePrivateProfileString接口來實現管理INI文件的&#xff0c;這個接口最久可以追溯到上個世紀80年代&#x…

政府數字化大屏系統 - Flask實現方案

下面我將設計一個基于Flask的政府數字化大屏系統&#xff0c;包含數據可視化、實時監控和統計分析功能&#xff0c;全套代碼下載看底部。 設計思路 使用Flask作為后端框架提供數據接口 前端采用響應式設計&#xff0c;適配大屏展示 使用ECharts實現多種數據可視化 模擬實時…

2025年主流開源音視頻播放項目深度解析

音視頻技術作為多媒體領域的核心支撐&#xff0c;其開源生態在近年來呈現爆發式發展。從底層編解碼引擎到跨平臺播放器應用&#xff0c;開源項目已形成完整的技術棧&#xff0c;滿足從個人娛樂到企業級流媒體服務的全場景需求。本文將深入剖析2025年最具影響力的五大開源音視頻…