Mybatis自查询递归查找子菜单
之前写过 java从数据库读取菜单,递归生成菜单树
今天才发现mybatis也可以递归查询子菜单
先看一下数据库
主键id,名称name,父id,和url 设计菜单类 public class Menu { // 菜单id private String id; // 父菜单id private String parentId; // 菜单名称 private String name; // 菜单url private String url; // 子菜单 private List<Menu> children; // 省去getter setter和toString方法 }
menuDao
public interface MenuDao { /** * 递归查找所有 * * @return */ public List<Menu> findAllRecursion(); }
mapper.xml
<resultMap type="Menu" id="recursionMenuMap"> <id column="id" property="id"/> <result column="name" property="name"/> <collection property="children" ofType="Menu" column="id" select="findMenuByParentId"/> </resultMap> <select id="findAllRecursion" resultMap="recursionMenuMap"> SELECT id,`name`,parent_id,url FROM menu WHERE parent_id ='' or parent_id is NULL ORDER BY `order` ASC </select> <select id="findMenuByParentId" resultType="Menu"> SELECT id,`name`,parent_id,url FROM menu WHERE parent_id = #{id} ORDER BY `order` ASC </select>
其中findAllRecursion会查询到所有的父菜单,
因为我们定义的
<select id="findAllRecursion" resultMap="recursionMenuMap">
而在recursionMenuMap中我们定义了如何去查找子菜单,调用findMenuByParentId