mybaits查询树形结构数据(递归)
业务中有一张数据库表中存放树形结构数据,查询时,根据EntityType的数据集合,需要查询出其对应的所有子级数据。其中数据库表结构如下:其中AbstractEntityID为id,AbstractEntityParentID为当前数据的父节点id,顶层节点的id为空。1. entity首先我们创建数据库表对应的entity,其内容如下:@Setter@Getterpublic class Abs
·
业务中有一张数据库表中存放树形结构数据,查询时,根据EntityType的数据集合,需要查询出其对应的所有子级数据。
其中数据库表结构如下:
其中AbstractEntityID为id,AbstractEntityParentID为当前数据的父节点id,顶层节点的id为空。
1. entity
首先我们创建数据库表对应的entity,其内容如下:
@Setter
@Getter
public class AbstractEntityTree {
/**
* 设备树类型
*/
private String entityType;
/**
* 树结构
*/
private String entityStructure;
/**
* 树id
*/
private String id;
/**
* 父节点id
*/
private String parentId;
/**
* code码
*/
private String code;
/**
* 名
*/
private String name;
/**
* 子节点
*/
private List<AbstractEntityTree> children;
}
其中children为当前对象自身。
2. mapper
<?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.xxx.xxx.mapper.common.AbstractEntityTreeMapper">
<!--AbstractEntityTree实体类与查询出的数据字段的映射-->
<resultMap id="baseResult" type="com.xxx.xxx.entity.AbstractEntityTree">
<id property="entityType" column="EntityType"/>
<id property="entityStructure" column="EntityStructure"/>
<id property="entityType" column="EntityType"/>
<id property="name" column="Name"/>
<id property="code" column="Code"/>
<id property="id" column="AbstractEntityID"/>
<id property="parentId" column="AbstractEntityParentID"/>
<association property="children" select="com.xxx.xxx.mapper.common.AbstractEntityTreeMapper.findTreeByParentId" column="AbstractEntityID" />
</resultMap>
<!--根据entityType获取设备树的信息(不传是获取所有的设备树信息)-->
<select id="findTreeByEntityTypeList" resultMap="baseResult">
SELECT * FROM AbstractEntityTree
<if test="entityTypes != null and entityTypes.size > 0">
WHERE EntityType IN
<foreach collection="entityTypes" open="(" separator="," close=")" item="entityType">
#{entityType}
</foreach>
</if>
</select>
<!--根据父节点id获取子设备树的信息-->
<select id="findTreeByParentId" resultMap="baseResult">
SELECT * FROM AbstractEntityTree WHERE AbstractEntityParentID = #{parentId}
</select>
</mapper>
更多推荐
已为社区贡献6条内容
所有评论(0)