Mybatis實現多級菜單查詢


寫在前面

最近實現一個小需求,前端需要菜單的信息,需要向后端發起獲取菜單的請求,菜單又是一個多級菜單,后端我用的mybatis進行數據庫查詢,實現的方法我這里想到有兩種,歡迎大家補充。

1. 在Menu類中添加屬性private List children

在菜單類中添加一個屬性private List<Menu> children 用來存儲子節點

package com.example.springbootvue.entity;

import java.io.Serializable;
import java.util.List;

import lombok.Data;

/**
 * sp_permission
 * @author 
 */
@Data
public class Menu implements Serializable {
    private Short psId;

    /**
     * 權限名稱
     */
    private String psName;

    /**
     * 父id
     */
    private Short psPid;

    /**
     * 控制器
     */
    private String psC;

    /**
     * 操作方法
     */
    private String psA;

    /**
     * 權限等級
     */
    private Object psLevel;

    /**
     * 子菜單列表
     */
    private List<Menu> children;

    /**
     * null
     */
    private String path;


    private static final long serialVersionUID = 1L;
}

在mapper接口中定義兩個方法

package com.example.springbootvue.mapper;

import com.example.springbootvue.entity.Menu;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface MenuMapper {
    /**
     * 獲取一級菜單
     * @param rootMenuId
     * @return
     */
    Menu getRootMenu(Integer rootMenuId);

    /**
     * 獲取子菜單
     * @param parentId
     * @return
     */
    List<Menu> findMenuByParentId(String parentId);
   
}

在resultMap中定義一個collection

    <resultMap id="menuMap" type="com.example.springbootvue.entity.Menu">
        <id column="ps_id" jdbcType="SMALLINT" property="psId"/>
        <result column="ps_name" jdbcType="VARCHAR" property="psName"/>
        <result column="ps_pid" jdbcType="SMALLINT" property="psPid"/>
        <result column="ps_c" jdbcType="VARCHAR" property="psC"/>
        <result column="ps_a" jdbcType="VARCHAR" property="psA"/>
        <result column="ps_level" jdbcType="OTHER" property="psLevel"/>
        <result column="path" jdbcType="VARCHAR" property="path"/>
        //這是關鍵語句,對應Menu類中的List<Menu> children字段
        <collection property="children" ofType="com.example.springbootvue.entity.Menu"
                    column="ps_id" select="findMenuByParentId"/>
    </resultMap>

這是關鍵代碼,對象Menu類中的List<Menu> children屬性

然后在menuMapper.xml實現mapper中的兩個方法

    <select id="getRootMenu" resultMap="menuMap" parameterType="integer">
        select *
        from sp_permission
        where ps_id = #{value}
    </select>

    <select id="findMenuByParentId" resultMap="menuMap" parameterType="string">
        select *
        from sp_permission
        where ps_pid = #{value}
    </select>

再貼上我數據庫的表結構


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM