若想直接通过sql实现多级关联查询表结构得有2 个必不可少的字段:id ,parentId,levelId
id:主键id,
parentId:父id
levelId:表示第几级(表本身关联查询的时候需要用到,不然会有重复数据)
利用mybatis collection 实现一对多关联查询
Dto:(一级)
public class ProvinceInfoDTO implements Serializable { private String id; private String name; private String pinyin; private String firstLetter; private List<CitysInfoDTO> cities; }
Dto:(二级)
public class CitysInfoDTO implements Serializable { private String id; private String name; private String pinyin; private String firstLetter; private String acronym; private List<RegionInfoDTO> regions; }
Dto(三级)
public class RegionInfoDTO implements Serializable { private String id; private String name; private String pinyin; private String firstLetter; }
resultMap
<resultMap id="unloadAreaQueryResultMap" type="com.haoyunhu.res.ProvinceInfoDTO"> // 一级 <result column="aid" property="id"/> <result column="aname" property="name"/> <result column="apinyin" property="pinyin"/> <result column="aletter" property="firstLetter"/> <collection property="cities" ofType="com.haoyunhu.res.CitysInfoDTO"> //二级 <result column="bid" property="id"/> <result column="bname" property="name"/> <result column="bpinyin" property="pinyin"/> <result column="bletter" property="firstLetter"/> <result column="bacronym" property="acronym"/> <collection property="regions" ofType="com.haoyunhu.res.RegionInfoDTO"> // 三级 <result column="cid" property="id"/> <result column="cname" property="name"/> <result column="cpinyin" property="pinyin"/> <result column="cletter" property="firstLetter"/> </collection> </collection> </resultMap>
省市区级联查询sql:
SELECT a.PROV_NAME,
b.PROV_NAME,
c.PROV_NAME
FROM T_DATA_AREAS a
LEFT JOIN T_DATA_AREAS b
ON a.id=b.PROV_PARENTID
LEFT JOIN T_DATA_AREAS C
ON b.id =C.PROV_PARENTID
WHERE a.PROV_LEVELTYPE=1
AND b.PROV_LEVELTYPE =2
AND c.PROV_LEVELTYPE =3
ORDER BY a.PROV_NAME;
以上mybatis的操作最终得到的json是:
{ "id":"310000", "name":"上海", "pinyin":"Shanghai", "firstLetter":"", "cities":[ { "id":"310100", "name":"上海市", "pinyin":"Shanghai", "firstLetter":"", "acronym":"", "regions":[ { "id":"230506", "name":"宝山区", "pinyin":"Baoshan", "firstLetter":"" } ] } ] }
一对多关联查询单边分页:
上述的这种关联查询时没法直接使用pagehelper分页插件的,因为pagehelper分页插件是针对真个sql 截取,所以只能手动分页(简单,分页无非就是截取sql +查询总条数),
所以若一对多关联查询想分页得针对主表(案例中的A表)截取sql(pageindex pagesize) ,再另外写条sql查询主表(案例中的A表)的记录数 ------注意mysql 的偏移量的概念
还需要注意的坑:
1:这种需要做级联查询,表结构又不满足的坑:若表结构不满足,但是又想省事,就得写sql 把原表整成这种固定格式的临时表结构(子查询)
2:电商领域的商品类目的级联查询和这个省市区的查询一样(都需要levelid,用在查询条件处:where a.levelid=0 and b.levelid=1 and c.levelid=2; 当然这种级联查询可以在java代码中可以实现,三条sql,分别查询 level =0 1 2的,然后java代码里面循环!
原文地址:https://www.cnblogs.com/YJZUUID/p/9295975.html