mybatis+mysql递归查询

时间:2022-06-01 20:19:47

前导:我们在开发过程中常用到递归查询,如菜单,一般我们都是用ztree实现菜单,但是数据查询时需要用到递归语句

建表:

create table menu{
	menu_Id  varchar(31),
	menu_name varchar(31),
	menu_level char(1),
	parent_Id varchar(31)
}
建JavaBean
package org.gtiles.components.courseinfo.unit.dao;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName Menu
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author huguangjun
 * @date 2016年6月28日 下午7:52:41
 */
public class Menu {
	public String menuId;
	public String menuName;
	public String menuLevel;
	public String parentId;
	public List<Menu> childList = new ArrayList<Menu>();
	public String getMenuId() {
		return menuId;
	}
	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}
	public String getMenuName() {
		return menuName;
	}
	public void setMenuName(String menuName) {
		this.menuName = menuName;
	}
	public String getMenuLevel() {
		return menuLevel;
	}
	public void setMenuLevel(String menuLevel) {
		this.menuLevel = menuLevel;
	}
	public String getParentId() {
		return parentId;
	}
	public void setParentId(String parentId) {
		this.parentId = parentId;
	}
	public List<Menu> getChildList() {
		return childList;
	}
	public void setChildList(List<Menu> childList) {
		this.childList = childList;
	}
	

}

1、orcle中递归查询语句

select t.id AS menuid,t.menu_name AS menuName,t.Parent_Id AS paterId from aut_menu_t t 
where 1=1 START WITH  t.menu_id='root'  connect by  t.Parent_Id=  PRIOR t.menu_id

2、 mybatis+mysql实现递归查询

	<!--查询所有,使用resultMap返回结果集,将数据组装成树形结构  -->
	 <select id="findMenuAll" resultMap="menu_map">
	 	select * from menu where menu_level='1'
	 </select>
	 <!-- 返回结果集 -->
	 <resultMap type="....entity.menu" id="menu_map">
	 	<id column="menu_id" property="menuId"/>
	 	<result column="menu_name" property="menu_name"/>
	 	<result column="menu_level" property="menuLevel"/>
	 	<collection property="childList"  column="menu_id " ofType="....entity.menu"
	 	 select="findMenuByparentId"></collection>
	 </resultMap>
	 
	 <!-- 根据父键查询 -->
	 <select id="findMenuByparentId" parameterType="String" resultMap="menu_map">
	 	select * from menu where parent_id=#{menuId}
	 </select>

将数据在mybatis xml文件中将数据就封装好,免得在java程序中再次获取数据

页面上读取数据则此处使用freemarker为列子

 <#list menulist as menu>
	${menu.menuName}
 	<#list menu.childList asmenuChild>
		${menuChild.menuName}
	<#list>
<#list>