关于mybatis递归查询树形结构的一点点...

害!这两天终于做了点和之前不一样的增删改查——树型结构,虽说是也没啥技术含量吧😂
首先,建立一个树型数据表,字段包括(id、sort_name、parent_id等)如图:
01
其次是实体类bean,如下

@Getter
@Setter
public class Sort {
    private Long id;
    private Long parentId;
    private String sortName;
    private Timestamp createTime;
    private Timestamp updateTime;

    @Transient
    private List<Sort> children;

然后编写SQL语句,如下:
① mapper

List<Sort> getAllSort();

② xml文件

    <resultMap id="BaseResultTreeMap" type="org.sang.bean.Sort">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="parent_id" jdbcType="BIGINT" property="parentId"/>
        <result column="parent_Name" jdbcType="VARCHAR" property="parentName"/>
        <result column="sort_name" jdbcType="VARCHAR" property="sortName"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
        <!--使用mybatis  collection 进行集合查询-->
        <collection property="children" ofType="Sort" select="selectTree" column="id" javaType="java.util.ArrayList"/>
    </resultMap>
    
    <!--父级查询-->
    <select id="getAllSort" resultMap="BaseResultTreeMap">
        select * from sort s where s.id in ('11','12','13','14')
    </select>
    
    <!--关联集合查询-->
    <select id="selectTree" parameterType="String" resultMap="BaseResultTreeMap">
        select * from sort s where s.parent_id=#{id}
    </select>

简单编写service部分,调用父级查询

    public List<Sort> selectTree() {
        return sortMapper.getAllSort();
    }

最后,简单controller实现🤔

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public List<Sort> getAllSorts() {
        return sortService.selectTree();
    }

🆗完工!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值