Introduction
The table of administrative divisions is a multi-level structure with similar designs. The general structure is as follows
Among them, code is the division number (primary key), parent_code is the parent division number, ancestors is the ancestor division number, and the query mainly focuses on the first two.
Inquire
(1) Hierarchical list, lazy query
When displaying, there is no need to query all the content at the beginning. Only all provinces, municipalities, autonomous regions, etc. need to be displayed to avoid long loading time.
In the returned entity class DTO, a hasChildren field is added to tell the front end whether there is a next level.
mybatis query
<select id="lazyTree" resultType="com.qhzz.csep.system.api.dto.RegionDTO">
SELECT
region.*,
( SELECT CASE WHEN count( 1 ) > 0 THEN 1 ELSE 0 END FROM bmp_region WHERE parent_code = region.code ) AS
"has_children"
FROM
bmp_region region
<where>
1=1
<if test="parentCode!=null">
and region.parent_code = #{parentCode}
</if>
</where>
</select>
search result
(2) Hierarchical list, use mybatis cascade query
Use the query method provided by mybatis to query multi-layer subsets at one time.
The entity class DTO adds a field, which is its own collection field
private List<RegionDTO> children;
The mapper.xml of mybatis is as follows. The selectByParentCode() method will query multi-layer content.
<resultMap id="regionResultMap" type="com.qhzz.csep.system.api.entity.Region">
<id column="code" property="code"/>
<result column="parent_code" property="parentCode"/>
<result column="ancestors" property="ancestors"/>
<result column="name" property="name"/>
<result column="province_code" property="provinceCode"/>
<result column="province_name" property="provinceName"/>
<result column="city_code" property="cityCode"/>
<result column="city_name" property="cityName"/>
<result column="district_code" property="districtCode"/>
<result column="district_name" property="districtName"/>
<result column="town_code" property="townCode"/>
<result column="town_name" property="townName"/>
<result column="village_code" property="villageCode"/>
<result column="village_name" property="villageName"/>
<result column="level" property="level"/>
<result column="sort" property="sort"/>
<result column="remark" property="remark"/>
</resultMap>
<resultMap id="resultMapWithChildren" type="com.qhzz.csep.system.api.dto.RegionDTO" extends="regionResultMap">
<collection property="children" ofType="com.qhzz.csep.system.api.dto.RegionDTO"
select="selectByParentCode" column="code"></collection>
</resultMap>
<select id="selectByParentCode" resultMap="resultMapWithChildren">
SELECT region.*
FROM bmp_region region
where region.parent_code = #{parentCode}
</select>
search result