主頁 > 後端開發 > MyBatis 結果映射總結

MyBatis 結果映射總結

2022-05-23 17:23:46 後端開發

前言

結果映射指的是將資料表中的欄位與物體類中的屬性關聯起來,這樣 MyBatis 就可以根據查詢到的資料來填充物體物件的屬性,幫助我們完成賦值操作,其實 MyBatis 的官方檔案對映射規則的講解還是非常清楚的,但考慮到自己馬上就會成為一名 SQL Boy,以后免不了經常跟 SQL 打交道(公司使用的也是 MyBatis),所以希望用更加通俗的語言對官方檔案所介紹的常用映射規則做一個總結,既為剛入門的同學提供一個參考,也方便自己以后查閱,本文會結合一些常見的應用場景,并通過簡單的示例來介紹不同的映射方法,如有理解錯誤,還請大家批評指正!

簡單欄位映射

MyBatis 中的 resultType 和 resultMap 均支持結果映射,對于一些簡單的映射操作,我們可以直接使用 resultType 來完成,但如果物體類中的屬性為復雜型別,或者屬性名和欄位名無法對應,那么我們就需要使用 resultMap 來創建自定義的映射關系,下面用一個示例來演示 resultType 和 resultMap 的使用方法,

首先創建物體類 User:

@Data
public class User {

    private int id;

    private String userName;

    private int age;

    private String address;

    private Date createTime;

    private Date updateTime;
}

然后創建 user 表:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `gmt_create` datetime(0) DEFAULT NULL,
  `gmt_modified` datetime(0) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

接著向 user 表中插入資料:

配置 MyBatis,啟用別名和駝峰式命名映射:

#application.yaml
mybatis:
  mapper-locations: classpath:mapper/*  # 指定 mapper.xml 檔案的路徑,該檔案用于撰寫 SQL 陳述句
  type-aliases-package: com.example.entity # 設定別名,它的作用是告訴 MyBatis 需要設定別名的物體類的所在的包,默認情況下,MyBatis 會使用物體類的非限定類名來作為它的別名,如將 com.example.entity.User 的別名設定為 User 或 user(別名不區分大小寫)
  configuration:
    map-underscore-to-camel-case: true # 開啟駝峰命名自動映射,如將資料表中的欄位 user_name 映射到物體物件的屬性 userName

創建 mapper 檔案,其內容如下:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
</resultMap>

<select id="findUserById" parameterType="Integer" resultMap="UserMap">
    select
    id,
    user_name,
    age,
    address,
    gmt_create,
    gmt_modified
    from user
    where id = #{id}
</select>

上述代碼中,我們使用 resultMap 來指定 SQL 陳述句的出參型別,默認情況下,如果資料表的欄位名與物體類的屬性名完全相同(如 id 對應 id),或者二者符合駝峰式命名映射的規則(如 user_name 對應 userName),那么 MyBatis 可以直接完成賦值操作,但 gmt_create 和 gmt_modified 不會映射為 createTime 和 updateTime,因此我們需要使用 resultMap 來創建新的映射關系,如果將 user 表的欄位 gmt_create 和 gmt_modified 分別改為 create_time 和 update_time,那么就可以使用 resulType="User"resulType="user" 來替換 resultMap="UserMap"

呼叫 findUserById(引數 id 等于 1)查詢用戶資訊,可得到如下結果:

{
    "address":"BUPT",
    "age":24,
    "createTime":1637164800000,
    "id":1,
    "updateTime":1637164800000,
    "userName":"John同學"
}

利用 constructor 指定構造方法

MyBatis 查詢出資料后,會呼叫物體類的無參構造方法創建物體物件,然后為該物件的屬性賦值,有時候我們會在物體類中多載多個構造方法,例如在不同的構造方法中執行不同的初始化操作,這種情況下我們希望 MyBatis 能夠呼叫指定的構造方法來初始化物件,此外,如果物體類中僅有帶參的構造方法,那么也需要通知 MyBatis 呼叫指定的構造方法,對于這兩個問題,我們可以使用 MyBatis 提供的 constructor 元素來解決,

MyBatis 官方檔案在介紹 constructor 時有提到,constructor 允許我們在始化物件時就為物件的屬性賦值,這樣可以不用暴露出公有方法,

首先在 User 類中添加帶參的構造方法:

public User(String userName, int age) {
    this.userName = userName;
    this.age = age;
}

然后將 mapper 檔案修改為:

<resultMap id="UserMap" type="User">
    <constructor>
        <arg column="user_name" javaType="String" />
        <arg column="age" javaType="_int"/>
    </constructor>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
</resultMap>

<select id="findUserById" parameterType="Integer" resultMap="UserMap">
    select
    id,
    user_name,
    age,
    address,
    gmt_create,
    gmt_modified
    from user
    where id = #{id}
</select>

注意,<arg> 標簽的定義順序必須與構造方法中的引數順序相同,因為 MyBatis 是根據 <constructor> 標簽中的引數型別串列來匹配物體類的構造方法的,例如在本例中,匹配的構造方法為 User.<init>(java.lang.String, int),如果將 xml 檔案中的兩個 <arg> 標簽互換位置,那么 User 物件將不會被實體化成功,因為 User 類中并沒有引數型別串列為 (int, java.lang.String) 的構造方法,如果我們不指定 javaType 屬性的值,那么 MyBatis 默認將其置為 Object,此時構造方法中對應的引數型別也必須為 Object,

MyBatis 中的 _int 型別對應 Java 中的 int 型別,int 型別對應 Integer 型別,

經過上述配置,MyBatis 在實體化物件的時候就會呼叫我們指定的構造方法,另外,MyBatis 也支持跟據引數名稱來匹配構造方法:

<resultMap id="UserMap" type="User">
    <constructor>
        <arg column="age" name="age" javaType="_int"/>
        <arg column="user_name" name="userName" javaType="String"/>
    </constructor>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
</resultMap>

<arg> 標簽中的 name 屬性用于設定構造方法的引數名稱,如果我們設定了 name 的值,那么 MyBatis 會根據該屬性匹配對應的構造方法,且 <arg> 標簽的位置可以隨意放置,上述代碼中,我們將兩個 <arg> 標簽互換位置,然后呼叫 findUserById,仍然可以查詢出用戶的資訊,

利用 association 關聯一個復雜型別

博客系統中,每個用戶都擔任著某種角色,如普通用戶、管理員、版主等,為了更好地描述用戶資訊,我們需要為 User 類添加一個 Role 型別的成員變數,記錄當前用戶所屬的角色,但 Role 型別與 String、int 等型別不同,Role 物件本身也存盤了一些特定的屬性,如 id、roleName 等,默認情況下 MyBatis 無法為這些屬性賦值,為了能夠正確初始化 Role 變數,我們需要使用 association 元素將查詢到的結果與 Role 物件的屬性關聯起來,

首先修改 User 類/創建 Role 類:


@Data
public class User {
    // 省略部分屬性
    private Role role;
}

@Data
public class Role {

    private int id;

    private String roleName;
    
    private Date createTime;

    private Date updateTime;
}

然后創建 role 表(存盤角色資訊)和 user_roles 表(存盤用戶和角色的關聯資訊):

# 創建 `role` 表
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `gmt_create` datetime(0) DEFAULT NULL,
  `gmt_modified` datetime(0) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

# 創建 `user_roles` 表
DROP TABLE IF EXISTS `user_roles`;
CREATE TABLE `user_roles`  (
  `id` int(11) NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `role_id` int(11) DEFAULT NULL,
  `gmt_create` datetime(0) DEFAULT NULL,
  `gmt_modified` datetime(0) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

接著向 role 表和 user_roles 表中插入資料:

MyBatis 為我們提供了三種處理子物件(如 Role 物件)的方式,分別為 嵌套結果映射嵌套查詢關聯多個結果集

1. 嵌套結果映射

嵌套結果映射 指的是在 resultMap 中嵌套一個映射關系,mapper 檔案的內容如下:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <association property="role" javaType="Role">
        <id column="role_id" jdbcType="INTEGER" property="id"/>
        <result column="role_name" jdbcType="VARCHAR" property="roleName"/>
    </association>
</resultMap>

<select id="findUserById" parameterType="Integer" resultMap="UserMap">
    select
    u.id,
    u.user_name,
    u.age,
    u.address,
    u.gmt_create,
    u.gmt_modified,
    r.id as 'role_id',
    r.role_name
    from user as u
    left join user_roles as ur on ur.user_id = u.id
    left join role as r on ur.role_id = r.id
    where u.id = #{id}
</select>

上述代碼中,我們將查詢到的 role_id 和 role_name 分別映射到 Role 物件(User 物件的屬性)的 id 和 roleName,

呼叫 findUserById 查詢用戶資訊,可得到如下結果:

{
    "address":"BUPT",
    "age":24,
    "createTime":1637164800000,
    "id":1,
    "role":{
        "id":1,
        "roleName":"管理員"
    },
    "updateTime":1637164800000,
    "userName":"John同學"
}

我們也可以將 association 中的映射關系獨立出來,改寫為如下形式,方便復用:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <association property="role" column="role_id" javaType="Role" resultMap="RoleMap"/>
</resultMap>

<resultMap id="RoleMap" type="Role">
    <id column="role_id" jdbcType="INTEGER" property="id"/>
    <result column="role_name" jdbcType="VARCHAR" property="roleName"/>
</resultMap>

2. 嵌套查詢

嵌套查詢 指的是在 resultMap 中嵌套一個查詢陳述句,mapper 檔案的內容如下:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <association property="role" javaType="Role" column="{user_id=id}" select="selectUserRole"/>
</resultMap>

<select id="selectUserRole" parameterType="Map" resultType="Role">
        select
        r.id,
        r.role_name
        from user_roles as ur
        left join role as r on ur.role_id = r.id
        where ur.user_id = #{user_id}
</select>

<select id="findUserById" parameterType="Integer" resultMap="UserMap">
        select
        id,
        user_name,
        age,
        address,
        gmt_create,
        gmt_modified
        from user
        where id = #{id}
</select>

resultMap 中嵌套了一個子查詢 selectUserRole,MyBatis 首先從 user 表中查詢出 id、user_name 等資訊,然后將 user_id 作為引數傳遞給 selectUserRoleselectUserRole 負責從 role 表和 user_roles 表中查詢出當前用戶的角色資訊,column="{user_id=id}" 指的是將查詢到的 id 賦值給變數 user_id,然后將 user_id 作為子查詢的入參(如果直接將 id 作為入參,那么 User 物件的 id 屬性將不會被賦值),如果需要傳入多個引數,那么可以使用一個復合屬性,如 column="{param1=value1, param2=value2}",注意,嵌套子查詢時,子查詢中的 parameterType 必須設定為 Map 或省略不寫,

3. 關聯多個結果集

關聯多個結果集 指的是一次性執行多個查詢陳述句,并得到多個結果集,然后利用某個結果集的資料來填充物件的屬性,

首先在 MySQL 資料庫中創建存盤程序 findUserAndRole:

-- 將結束標志符更改為 $$
delimiter $$
create procedure findUserAndRole(in user_id int)
begin
	select
	id,
	user_name,
	age,
	address,
	gmt_create,
	gmt_modified
	from user
	where id = user_id;
	
	select 
	r.id as role_id, 
	r.role_name as role_name, 
	ur.user_id as user_id 
	from user_roles as ur 
	left join role as r 
	on ur.role_id = r.id;
end $$
-- 將結束標志符改回 ;
delimiter ;

然后修改 mapper 檔案的內容:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <association property="role" javaType="Role" resultSet="role" column="id" foreignColumn="user_id">
        <id column="role_id" jdbcType="INTEGER" property="id"/>
        <result column="role_name" jdbcType="VARCHAR" property="roleName"/>
    </association>
</resultMap>

<select id="findUserById" parameterType="Integer" resultSets="user,role" resultMap="UserMap" statementType="CALLABLE">
        {call findUserAndRole(#{user_id,jdbcType=INTEGER,mode=IN})}
</select>

解釋一下上述操作的含義,我們在存盤程序 findUserAndRole 中定義了兩條 SQL 陳述句,第一條的執行邏輯是利用 user_id 從 user 表中查詢出當前用戶的 id,user_name 等資訊;第二條的執行邏輯是利用關聯查詢從 role 表和 user_roles 表中查詢出 user_id、role_id 以及 role_name 等資訊,我們將兩次查詢得到的結果集分別表示為 user 和 role,即 resultSets="user,role",然后通過 association 將結果集 role 中的 role_id 和 role_name 分別映射到 Role 物件的 id 和 roleName 屬性,column="id" foreignColumn="user_id" 用于關聯兩個結果集中的資料,因為結果集 role 中包含了所有用戶的角色資訊(雖然本例中我們只設定了一個用戶,但實際上結果集 role 中包含著所有用戶的資訊),因此在進行屬性填充之前,我們需要指明利用哪一個角色資訊進行屬性填充,column="id" foreignColumn="user_id" 的作用就是從結果集 role 中篩選出 user_id 為 id 的角色資訊,

resultSets 中不同的結果集之間用逗號分隔,中間千萬不能加空格!

利用 collection 關聯多個復雜型別

上文中我們分析了一個用戶擔任一種角色的情況,然而在實際開發中,每個用戶都有可能同時擔任多種角色,例如 "John同學" 既可以是管理員,又可以是版主,此時使用 association 無法正確查詢出用戶的角色資訊,因為 association 處理的是一對一的映射關系,當需要關聯多個物件時,我們需要使用 collection 元素,

首先修改物體類:

@Data
public class User {
    // 省略部分屬性
    private List<Role> roles;
}

然后在 user_roles 表中插入一條記錄:

collection 的使用方法和 association 非常相似,在上文中介紹的三種方法中,我們只需要做一些簡單的修改,就可以查詢出用戶的所有角色資訊,

1. 嵌套結果映射

mapper 檔案的內容如下:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <collection property="roles" ofType="Role">
        <id column="role_id" jdbcType="INTEGER" property="id"/>
        <result column="role_name" jdbcType="VARCHAR" property="roleName"/>
    </collection>
</resultMap>

<select id="findUserById" parameterType="Integer" resultMap="UserMap">
    select
    u.id,
    u.user_name,
    u.age,
    u.address,
    u.gmt_create,
    u.gmt_modified,
    r.id as 'role_id',
    r.role_name
    from user as u
    left join user_roles as ur on ur.user_id = u.id
    left join role as r on ur.role_id = r.id
    where u.id = #{id}
</select>

與上文中使用 association 嵌套結果映射的區別在于,我們將 javaType 替換為了 ofType,以此來指定 Java 集合中的泛型型別,

呼叫 findUserById 查詢用戶資訊,可得到如下結果:

{
    "address":"BUPT",
    "age":24,
    "createTime":1637164800000,
    "id":1,
    "roles":[
        {
            "id":1,
            "roleName":"管理員"
        },
        {
            "id":2,
            "roleName":"版主"
        }
    ],
    "updateTime":1637164800000,
    "userName":"John同學"
}

2. 嵌套查詢

mapper 檔案的內容如下:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <collection property="roles" ofType="Role" column="user_id=id" select="selectUserRole"/>
</resultMap>

<select id="selectUserRole" parameterType="Map" resultType="Role">
        select
        r.id,
        r.role_name
        from user_roles as ur
        left join role as r on ur.role_id = r.id
        where ur.user_id = #{user_id}
</select>

<select id="findUserById" parameterType="Integer" resultMap="UserMap">
        select
        id,
        user_name,
        age,
        address,
        gmt_create,
        gmt_modified
        from user
        where id = #{id}
</select>

同樣地,我們將 javaType 改為 ofType,

3. 關聯多個結果集

mapper 檔案的內容如下:

<resultMap id="UserMap" type="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="address" jdbcType="VARCHAR" property="address"/>
    <result column="gmt_create" jdbcType="DATE" property="createTime"/>
    <result column="gmt_modified" jdbcType="DATE" property="updateTime"/>
    <collection property="roles" ofType="Role" resultSet="roles" column="id" foreignColumn="user_id">
        <id column="role_id" jdbcType="INTEGER" property="id"/>
        <result column="role_name" jdbcType="VARCHAR" property="roleName"/>
    </collection>
</resultMap>

<select id="findUserById" parameterType="Integer" resultSets="user,roles" resultMap="UserMap" statementType="CALLABLE">
        {call findUserAndRole(#{user_id,jdbcType=INTEGER,mode=IN})}
</select>

同理,存盤程序中的執行邏輯保持不變,只需將 javaType 改為 ofType,

改用 collection 后,還要注意將 property 由 role 改為 roles,當然,這個名稱可自由定義,

查詢具有樹形結構的資料

樹形結構資料在實際開發中非常常見,比較典型的就是選單表,每個父選單都可能包含一個或多個子選單,而每個子選單也可能包含孫子選單,有時候我們希望查詢出某個選單下的所有子選單,并分級展示,這種情況應該如何處理呢?其實上文中介紹的三種方法均支持多級結果映射,我們只需要在 mapper 檔案中做一些簡單的處理,

首先創建 Menu 類:

@Data
public class Menu {

    private long id;

    private String name;

    private long parentId;

    private List<Menu> childMenus;

   private Date createTime;

   private Date updateTime;
}

然后創建 menu 表:

DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu`  (
  `id` int(11) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `gmt_create` datetime(0) DEFAULT NULL,
  `gmt_modified` datetime(0) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

接著向 menu 表中插入資料:

為了更直觀地展示各層級選單之間的關系,我們將資料整理在下面的表格中:

id name parent_id
1 文章 0
11 所有文章 1
12 寫文章 1
121 載入草稿 12
2 用戶 0
21 個人資料 2
3 附件 0

可以看到,選單表總共有三個層級(不包含第 0 級),第一級的 "所有文章" 下有子選單 "寫文章",第二級的 "寫文章" 下有子選單 "載入草稿",每個層級的選單都可能有零個、一個或多個子選單,為了將所有的選單查詢出來,我們既要修改 SQL 陳述句,又要修改 resultMap 中的映射關系,下面介紹三種查詢方式,

1. 嵌套結果映射

mapper 檔案的內容如下:

<resultMap id="menuMap" type="Menu">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="parent_id" property="parentId"/>
    <collection property="childMenus" ofType="Menu">
        <id column="id2" jdbcType="INTEGER" property="id"/>
        <result column="name2" jdbcType="VARCHAR" property="name"/>
        <result column="parent_id2" jdbcType="INTEGER" property="parentId"/>
        <collection property="childMenus" ofType="Menu">
            <id column="id3" jdbcType="INTEGER" property="id"/>
            <result column="name3" jdbcType="VARCHAR" property="name"/>
            <result column="parent_id3" jdbcType="INTEGER" property="parentId"/>
        </collection>
    </collection>
</resultMap>

<select id="findMenus" parameterType="Map" resultMap="menuMap">
    select
    m1.id as id,
    m1.name as name,
    m1.parent_id as parent_id,
    m2.id as id2,
    m2.name as name2,
    m2.parent_id as parent_id2,
    m3.id as id3,
    m3.name as name3,
    m3.parent_id as parent_id3
    from
    menu as m1
    left join menu as m2 on m1.id = m2.parent_id
    left join menu as m3 on m2.id = m3.parent_id
    where m1.parent_id = #{menu_id}
</select>

因為選單表中最多有三個層級,所以我們在 SQL 陳述句中使用了三表聯查,分別從表 m1、m2、m3(均為 menu 表)中查詢出各個級別(從上到下)的選單,然后在 collection 中新增一個嵌套,表 m2 和表 m3 中查出的資料均用于填充前一級別的 childMenus 屬性,

呼叫 findMenus(引數 menu_id 等于 0)查詢選單資訊,可得到如下結果:

[
    {
        "childMenus":[
            {
                "childMenus":[
                    {
                        "id":121,
                        "name":"載入草稿",
                        "parentId":12
                    }
                ],
                "id":12,
                "name":"寫文章",
                "parentId":1
            },
            {
                "childMenus":[

                ],
                "id":11,
                "name":"所有文章",
                "parentId":1
            }
        ],
        "id":1,
        "name":"文章",
        "parentId":0
    },
    {
        "childMenus":[
            {
                "childMenus":[

                ],
                "id":21,
                "name":"個人資料",
                "parentId":2
            }
        ],
        "id":2,
        "name":"用戶",
        "parentId":0
    },
    {
        "childMenus":[

        ],
        "id":3,
        "name":"附件",
        "parentId":0
    }
]

注意,嵌套結果映射 的方式不具備通用性,因為選單表的結構可能不止三層,如果有多個層級的選單,那么我們就需要繼續修改 SQL 陳述句并新增嵌套,

2. 嵌套查詢

mapper 檔案的內容如下:

<resultMap id="menuMap" type="Menu">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="parent_id" property="parentId"/>
    <collection column="{menu_id=id}" property="childMenus" ofType="Menu" select="findMenus"/>
</resultMap>

<select id="findMenus" parameterType="Map" resultMap="menuMap">
    select
    id,
    name,
    parent_id
    from
    menu
    where parent_id = #{menu_id} 
</select>

上述代碼中,我們將嵌套的子查詢設定為 findMenus 本身,MyBatis 首先呼叫 findMenus 查詢出 parent_id 為 menu_id 的選單,然后將查詢出的選單的 id 賦值給 menu_id,繼續呼叫 findMenus 查詢出下一層級的選單,此種方式可以遞回的查詢出所有選單,無論選單表有多少個層級,

3. 關聯多個結果集

首先創建存盤程序 findMenu:

delimiter $$
create procedure findMenu(in menu_id int)
begin
	select
	id as id1,
	name as name1,
	parent_id as parent_id1
	from menu
	where parent_id = menu_id;
	
	select
	id as id2,
	name as name2,
	parent_id as parent_id2
	from menu;
	
	select
	id as id3,
	name as name3,
	parent_id as parent_id3
	from menu;
	
end $$
-- 將結束標志符改回 ;
delimiter ;

然后將 mapper 檔案的內容修改為:

<resultMap id="MenuMap" type="Menu">
    <id column="id1" property="id"/>
    <result column="name1" property="name"/>
    <result column="parent_id1" property="parentId"/>
    <collection property="childMenus" ofType="Menu" resultSet="menu2" column="id1" foreignColumn="parent_id2">
        <id column="id2" jdbcType="INTEGER" property="id"/>
        <result column="name2" jdbcType="VARCHAR" property="name"/>
        <result column="parent_id2" property="parentId"/>
        <collection property="childMenus" ofType="Menu" resultSet="menu3" column="id2" foreignColumn="parent_id3">
            <id column="id3" jdbcType="INTEGER" property="id"/>
            <result column="name3" jdbcType="VARCHAR" property="name"/>
            <result column="parent_id3" property="parentId"/>
        </collection>
    </collection>
</resultMap>

<select id="findMenus" parameterType="Map" resultSets="menu1,menu2,menu3" resultMap="MenuMap" statementType="CALLABLE">
        {call findMenu(#{menu_id,jdbcType=INTEGER,mode=IN})}
</select>

findMenu 中定義了三條 SQL 陳述句,第一條的執行邏輯是從 menu 表中查詢出 parent_id 為 menu_id 的選單,其它兩條的執行邏輯是從 menu 表中查詢出所有的選單,我們將三條查詢回傳的結果集分別表示為 menu1、menu2 和 menu3,然后利用 menu2 和 menu3 中的資料分別填充子選單和孫子選單的屬性,

關聯多個結果集嵌套結果映射 一樣,在查詢樹形結構資料時不具備通用性,若選單表的層級大于 3,那么我們就需要修改存盤程序和映射關系,

參考資料

MyBatis 官方檔案
Mybatis 中強大的 resultMap

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479991.html

標籤:其他

上一篇:Python資料分析--Numpy常用函式介紹(2)

下一篇:Hibernate基礎入門

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more