Mybatis通过collection递归查询菜单树的实现方法

在业务开发中我们可能会遇到菜单树的查询之类的需求,即实体中包含本实体的list或数组,层数不定,下面为借助Mybatis的collection的一种方法

现有表结构如下

 domain如下

package tech.niua.auth.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SysResource {
    @TableId(type= IdType.AUTO)
    private Long id;

    private String name;

    private Integer orderNum;

    private String permission;

    private Integer type;

    private String url;

    private Long parentId;

    private Boolean available;

    @TableField(exist=false)
    private List<SysResource> childResources;

}

xml我们这样写

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="tech.niua.auth.mapper.SysResourceMapper">
  <resultMap id="BaseResultMap" type="tech.niua.auth.domain.SysResource">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="available" jdbcType="BIT" property="available" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="order_num" jdbcType="INTEGER" property="orderNum" />
    <result column="permission" jdbcType="VARCHAR" property="permission" />
    <result column="type" jdbcType="INTEGER" property="type" />
    <result column="url" jdbcType="VARCHAR" property="url" />
    <result column="parent_id" jdbcType="BIGINT" property="parentId" />
   <!--连接查询,获取子栏目的资源信息-->
  <collection property="childResources" column="id" ofType="tech.niua.auth.domain.SysResource" select="selectResourceByParentId" />
  </resultMap>
  <sql id="Base_Column_List">
    id, available, name, order_num, permission, type, url, parent_id
  </sql>
    <select id="selectResourceByParentId" parameterType="java.lang.Long"  resultMap="BaseResultMap">
        SELECT
        sys_resource.id as id,
        sys_resource.available as available,
        sys_resource.`name` as name ,
        sys_resource.permission as permission,
        sys_resource.order_num as order_num,
        sys_resource.type as type,
        sys_resource.url as url,
        sys_resource.parent_id as parent_id
        FROM
        sys_resource
        where parent_id = #{id} order by order_num
  </select>
</mapper>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeXu_cyber

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值