Mybatis递归自查询查(无限极分类)
无限极分类
bean:没有写全,明白什么意思就行
public class
Category implements Serializable {
private Integer categoryId;
private String categoryName;
private Integer parentId;
private List<Category> children;
}
mapper类
List<Category> getRootCategory(); // 获取一级菜单,顶级菜单
List<Category> getCategoryByParentId(Integer parentId); //根据父一级菜单,返回所有子菜单
mapper.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="com.mall.mapper.CategoryMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.mall.beans.Category">
<id column="category_id" property="categoryId"/>
<result column="category_name" property="categoryName"/>
<!--
这句语句的作用相当于调用 getCategoryByParentId(category_id的值) 方法,返回的数据赋值给children,数据的类型是oftype的值
这个不一定非得用于无限极分类, 这句话的作用其实就是调用个方法给字段赋值
-->
<collection column="category_id" property="children" ofType="com.mall.beans.Category" select="getCategoryByParentId"/>
</resultMap>
<select id="getRootCategory" resultMap="BaseResultMap">
SELECT *
from category c
where c.parent_id = 0
</select>
<select id="getCategoryByParentId" resultMap="BaseResultMap" >
select * from category c where parent_id=#{parentId}
</select>
</mapper>
这实现了效果,原理就是不断调用自身然后赋值给·children·
当然了,如果是三级分类或者二级分类的话可以用sql语句直接实现
三级分类用sql语句怎么写(多级分类的写法)