1. 简介
对于树结构数据,通过mybatis的 mapper的xml文件实现递归查询.
一般每条记录都有一个类似parentId的字段
2. Mapper接口
@Mapper
public interface XxxpMapper extends BaseMapper<XxxPo> {
/**
* 获取完整树
*/
List<XxxPo> getTree(@Param("parentId") String parentId);
}
3. xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.XXXMapper">
<resultMap type="com.po.XxxPo" id="xxxTreeResultMap" extends="drawGroupResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="parentId" column="parent_id"/>
<collection property="childList" ofType="drawGroupTreeResultMap"
select="getTree"
<!-- 当前记录的ID为子记录的父ID -->
column="{projectId=project_id,parentId=id}">
</collection>
</resultMap>
<select id="getTree" resultMap="drawGroupTreeResultMap">
SELECT * FROM table_name WHERE
AND project_id = #{projectId}
<if test="parentId != null and parentId != ''">
AND parent_id = #{parentId}
</if>
<if test="parentId == null or parentId == ''">
AND (parent_id IS NULL OR parent_id ='')
</if>
</select>
</mapper>